Java PrintWriter FileNotFound

我在写入txt文件时遇到问题。 我得到一个FileNotFoundexception,但我不知道为什么因为该文件肯定是存在的。 这是代码。

import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.File; public class Save { public static void main(String[] args) { File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt"); PrintWriter pw = new PrintWriter(file); pw.println("Hello World"); pw.close(); } } 

在创建PrintWriter put之前,必须使用其目录创建实际文件

 file.mkdirs(); file.createNewFile(); 

使用正确的try和catch块看起来像这样……

 import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.File; public class Save { public static void main(String[] args) { File file = new File("save.txt"); try { file.mkdirs(); file.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } try { PrintWriter pw = new PrintWriter(file); pw.println("Hello World"); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } 

只是因为你知道文件在那里,并不意味着你的代码在尝试处理之前不应该检查它的存在。

就FileNotFoundexception而言,如果IDE检测到exception可能发生,则有些(如果不是全部)Java IDE强制您编写try / catch块。

例如NetBeans,代码甚至不会编译:

在此处输入图像描述

您必须编写try / catch块代码来处理潜在的exception

 public static void main(String[] args) { File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt"); if (file.exists()) { try { PrintWriter pw = new PrintWriter(file); pw.println("Hello World"); pw.close(); } catch (FileNotFoundException fnfe){ System.out.println(fnfe); } } }