gpt4 book ai didi

java - 为什么此输出会打印一个空白文件?

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:12 26 4
gpt4 key购买 nike

这个小代码片段应该输出一个包含文本的文件:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com