FileInputStream和FileOutputStream如何在Java中工作?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了FileInputStream和FileOutputStream如何在Java中工作?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2218字,纯文字阅读大概需要4分钟。
内容图文
![FileInputStream和FileOutputStream如何在Java中工作?](/upload/InfoBanner/zyjiaocheng/819/9fb2ead71a594cb5b5ed090ebea44b9a.jpg)
我在Java Tutorials Docs上阅读java中的所有输入/输出流.教程编写者使用这个例子:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
xanadu.txt文件数据:
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
输出到outagain.txt文件:
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
>为什么即使我们正在阅读字符,作者也会使用int c?
>为什么在条件下使用-1?
> out.write(c)如何;方法将int转换为再次字符?
解决方法:
1: Now I want to ask why writer use int c? even we are reading characters.
FileInputStream.read()将一个字节的数据作为int返回.这是有效的,因为一个字节可以表示为int而不会损失精度.请参阅this answer以了解为什么返回int而不是byte.
2: The second why use -1 in while condition?
到达文件末尾时,返回-1.
3: How out.write(c); method convert int to again characters? that provide same output in outagain.txt file
FileOutputStream.write()将byte参数作为int.由于int跨越多于一个字节的值,因此忽略给定int的24个高位,使其成为字节兼容的值:Java中的int是always 32 bits.通过删除24个高位,你’重新下降到8位值,即一个字节.
我建议你仔细阅读每种方法的Javadocs.作为参考,他们回答了您的所有问题:
read:
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.
内容总结
以上是互联网集市为您收集整理的FileInputStream和FileOutputStream如何在Java中工作?全部内容,希望文章能够帮你解决FileInputStream和FileOutputStream如何在Java中工作?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。