(1)
OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream("A.txt"));
ows.write('a');
(2)
FileOutputStream fos = new FileOutputStream("B.txt");
fos.write('a');
(2)可以成功写'a',但(1)不能。谁能告诉我为什么?
答案 0 :(得分:2)
它们都可以向文件中写入字节/字符(对于OutputStream
,您实际上是在写byte
,而Writer
是char
)
您的特殊问题是您没有 close()
输出流,为了将数据刷新到磁盘,应该始终执行输出流。
Writer
的缓冲区很小。您可以通过调用flush()
或将其关闭来强制刷新。
OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream("a.txt"));
ows.write('a');
ows.close();
FileOutputStream fos = new FileOutputStream("b.txt");
fos.write('b');
fos.close();
或更妙的是:
try (OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream("a.txt"))) {
ows.write('a');
}
try (FileOutputStream fos = new FileOutputStream("b.txt")) {
fos.write('b');
}