为什么FileOutputStream的write()方法可以写一个字符但是OutputStreamWriter不能?

时间:2018-04-20 11:18:07

标签: java

(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)不能。谁能告诉我为什么?

1 个答案:

答案 0 :(得分:2)

它们都可以向文件中写入字节/字符(对于OutputStream,您实际上是在写byte,而Writerchar

您的特殊问题是您没有 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');
}