0

我有以下代码,但是当我检查输出文件时,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);
    }
  }
}
4

2 回答 2

3

您需要关闭最外层的 I/O 包装器。

代替

ostream.close();

经过

writer.close();

与具体问题无关DataOutputStream,在这种情况下,这些和DataInputStream包装器是不必要的。删除它们。最后,您应该在一个finally块中关闭流。另请参阅此相关问题:我是否必须关闭由 PrintStream 包装的 FileOutputStream?

于 2011-11-11T01:25:00.820 回答
0

它使作者仍然没有将缓冲区刷新到 ostream。您可以使用 writer.flush(); 像这样

writer.write(cc, 0, 300);
writer.flush();
于 2011-11-11T01:34:44.587 回答