我有一个简单的设置,我想写一个名为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!");
}
}
这是什么问题?我似乎无法弄明白。 感谢
答案 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);
}
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();
}