Java WriteFile无法查看内容

时间:2014-05-04 09:16:01

标签: java io

我想创建一个包含一些文本的简单文本文件。

import java.io.*;

class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);

    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
        }
      }
    }

  } 

public static void main(String args[]){
    writeTextFile("myText.txt","some text");
}
}

当我运行此代码时,我成功创建了文本文件,但是当我打开它时,我看不到内容("一些文字")。我究竟做错了什么?

1 个答案:

答案 0 :(得分:5)

您正在关闭基础FileWriter,但实际数据仍然存储(缓存)在BufferedWriter对象中。这是你必须关闭的对象:

FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();