Java PrintWriter FileNotFound

2019-05-04 18:47发布

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();
    }
}

2条回答
smile是对你的礼貌
2楼-- · 2019-05-04 19:22

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();
        }

    }
}
查看更多
We Are One
3楼-- · 2019-05-04 19:32

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:

enter image description here

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);
        }
    }
}
查看更多
登录 后发表回答