Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 269
user3720913 Avatar asked Apr 18 '15 18:04

user3720913


2 Answers

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

    }
}
like image 144
Daniel K. Avatar answered Sep 21 '22 14:09

Daniel K.


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);
        }
    }
}
like image 38
Shar1er80 Avatar answered Sep 22 '22 14:09

Shar1er80