我正在阅读有关 java 中的所有输入/输出流的信息Java 教程文档 https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html。教程作者使用这个例子:
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
即使我们正在阅读字符?
Why use -1
在 while 条件下?
How out.write(c);
方法转换int
再次字符?
1:现在我想问作者为什么使用int c?甚至我们在读字符。
FileInputStream.read() http://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html#read--返回一个字节的数据作为int
。这是可行的,因为一个字节可以表示为int
且不损失精度。看这个答案 https://stackoverflow.com/a/4659706/1743880理解为什么int
返回而不是byte
.
2:第二个为什么在while条件下使用-1?
当到达文件末尾时,返回-1。
3:如何out.write(c);方法将 int 再次转换为字符?在 outagain.txt 文件中提供相同的输出
FileOutputStream.write() http://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html#write-int-接受一个字节参数作为int
。自从int
跨越的值多于一个字节,给定 int 的 24 个高位将被忽略,使其成为字节兼容的值:int
在Java中是始终为 32 位 https://stackoverflow.com/a/1032988/1743880。通过删除 24 个高位,您可以减少到 8 位值,即一个字节。
我建议您仔细阅读每个方法的 Javadocs。作为参考,他们回答了您的所有问题:
read http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#read--:
从输入流读取下一个数据字节。值字节以 0 到 255 范围内的 int 返回。如果由于已到达流末尾而没有可用字节,则返回值 -1。此方法会阻塞,直到输入数据可用、检测到流结束或引发异常为止。
write http://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html#write-int-:
将指定字节写入此输出流。写入的一般约定是将一个字节写入输出流。要写入的字节是参数 b 的低 8 位。 b 的 24 个高位被忽略。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)