这个小代码片段应该输出一个包含文本的文件:
public static void main(String[] args) {
try{
Path gabblePath = Paths.get("C:/Users/AlterionX/Documents/"
+ "NetBeansProjects/File Creator, Function Example/src/file/"
+ "gabble.txt");
Charset cs = Charset.defaultCharset();
Scanner scanner = new Scanner(System.in);
String total = scanner.nextLine();
System.out.println(total);
BufferedWriter writer = Files.newBufferedWriter(gabblePath, cs);
writer.write(total);
System.out.println("total printed");
}catch(IOException ex){
System.out.println("IO Exception");
}
System.exit(0);
}
相反,它创建并返回一个空白文件。它成功运行,而所有其他内容,它只是创建一个空白文件。
我应该关闭扫描仪还是其他原因?
编辑 我拿出扫描仪改成实际的字符串,还是不行。
最佳答案
关闭Writer
并确保无条件地执行此操作(即finally block )。
public static void main(String[] args) {
BufferedWriter writer = null;
try{
Path gabblePath = Paths.get("C:/Users/AlterionX/Documents/"
+ "NetBeansProjects/File Creator, Function Example/src/file/"
+ "gabble.txt");
Charset cs = Charset.defaultCharset();
Scanner scanner = new Scanner(System.in);
String total = scanner.nextLine();
System.out.println(total);
writer = Files.newBufferedWriter(gabblePath, cs);
writer.write(total);
System.out.println("total printed");
}catch(IOException ex){
System.out.println("IO Exception");
} finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException e) { /* ignore */ }
}
}
System.exit(0);
}
我认为在 Java 7 或 8 中,有一种更干净的方法来处理 finally 清理代码中的 try/catch,但我还没有使用过它,所以我不确定。
关于java - 为什么此输出会打印一个空白文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22548980/