我有以下代码,但是当我检查输出文件时,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);
}
}
}
最佳答案
您需要关闭最外面的 I/O 包装器。
替换
ostream.close();
由
writer.close();
<小时/>
与具体问题无关,这些 DataOutputStream
和 DataInputStream
包装器在此上下文中是不必要的。删除它们。最后,您应该在finally
block 中关闭流。另请参阅此相关问题:Do I have to close FileOutputStream which is wrapped by PrintStream?
关于java - char[] 上的流写入器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088578/