Java PrintWriter FileNotFound

谁说胖子不能爱 提交于 2020-01-01 10:27:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!