我正在阅读关于Java中所有输入/输出流的内容,参考Java Tutorials Docs。教程作者使用了以下示例:
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
?为什么在while条件中使用
-1
?out.write(c);
方法如何将int
再次转换为字符?
FileInputStream
和FileOutputStream
。当你不确定为什么会调用某个方法时,从中学习很重要。 - RealSkeptic