问题
I'm having trouble with writing to a txt file. I am getting a FileNotFound Exception, but I don't know why because the file most definitely is there. Here is the code.
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();
}
}
回答1:
You must create the actual file with its directory before you create the PrintWriter
put
file.mkdirs();
file.createNewFile();
Using this with the proper try and catch blocks would look something like this...
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();
}
}
}
回答2:
Just because you know the file is there, doesn't mean your code should not check for its existence before attempting to process.
As far as your FileNotFound Exception, some if not all Java IDEs force you to write try/catch blocks if the IDE detects that an exception can occur.
NetBeans for example, The code won't even compile:
You have to code a try/catch block to handle a potential 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);
}
}
}
来源:https://stackoverflow.com/questions/29720934/java-printwriter-filenotfound