Search code examples
javafileprintwriter

Java PrintWriter FileNotFound


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

Solution

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