Java outputStream无法正常工作

时间:2014-10-26 02:00:03

标签: java outputstream

我有一个简单的设置,我想写一个名为file.txt的文件。但是,当我运行代码时,没有任何内容写入该文件。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class rand {
    public static void main(String[] args) {
    PrintWriter outputStream = null;

    try {
        outputStream = new PrintWriter(new FileOutputStream("file.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        System.exit(0);
    }
    outputStream.println("Hello World!");
}
}

这是什么问题?我似乎无法弄明白。 感谢

1 个答案:

答案 0 :(得分:2)

您没有关闭PrintWriter。您可以使用try-with-resources语句

来解决这个问题
try (outputStream = new PrintWriter(new FileOutputStream("file.txt"));) {
  outputStream.println("Hello World!");  
} catch (FileNotFoundException e) {
  System.out.println("File not found");
  System.exit(0);
}

finally block

try {
  outputStream = new PrintWriter(new FileOutputStream("file.txt"));
  outputStream.println("Hello World!");  
} catch (FileNotFoundException e) {
  System.out.println("File not found");
  System.exit(0);
} finally {
  outputStream.close();
}