我有以下代码,但是当我检查输出文件时,似乎没有写入char [] cc。有人能告诉我什么是错的吗?
import java.io.*;
class Test {
public static void main(String[] args) {
System.out.printf("start of main\n");
char[] cc = new char[300];
try {
String s = "this is a test.";
System.arraycopy(s.toCharArray(), 0, cc, 0, s.length());
System.out.printf("cc = %s\n", new String(cc));
String filename = "tst.data";
DataOutputStream ostream = new DataOutputStream(new FileOutputStream(filename));
OutputStreamWriter writer = new OutputStreamWriter(ostream);
writer.write(cc, 0, 300);
ostream.close();
DataInputStream istream = new DataInputStream(new FileInputStream(filename));
InputStreamReader reader = new InputStreamReader(istream);
char[] newcc = new char[300];
reader.read(newcc, 0, 300);
istream.close();
System.out.printf("newcc = %s\n", new String(newcc));
} catch (Exception e) {
System.out.printf("Exception - %s\n", e);
}
}
}
答案 0 :(得分:3)
您需要关闭最外层的I / O包装器。
替换
ostream.close();
通过
writer.close();
无关,在此上下文中不需要那些DataOutputStream
和DataInputStream
包装器。删除它们。最后,您应该在finally
块中关闭流。另请参阅此相关问题:Do I have to close FileOutputStream which is wrapped by PrintStream?
答案 1 :(得分:0)
它接缝仍然没有将缓冲区刷新到ostream。 你可以使用writer.flush(); 像这样
writer.write(cc, 0, 300);
writer.flush();