Alexis R Devitre
Alexis R Devitre

Reputation: 298

File Not Found Exception using Java FileWriter

I am trying to write to a txt file from a JAVA Application. I have tried using Buffered Writer, then just FileWriter to create a new file within a potentially new (not indefinitely since more files with different names will be later programatically written there by the same method) subfolder. I get the following error message (It's actually much longer but I think this is the key part of it):

java.io.FileNotFoundException: src/opinarium3/media/presentaciones/Los fantasmas del Sistema Solar/comments/2014-07-26.txt (No such file or directory) at java.io.FileOutputStream.open(Native Method)

And this is the code firing the issue (it activates as you press a button to register a comment having been filled in a custom form):

private void fileCommentOnPresentation(String title, String positiveComments, String negativeComments, int grade) throws IOException{
    FileWriter bw;
    try{
        bw = new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/"+Date.valueOf(LocalDate.now())+".txt");
        bw.write(title+"\n"+positiveComments+"\n"+negativeComments+"\n"+grade);
        bw.flush();
        bw.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

Upvotes: 4

Views: 16989

Answers (3)

laune
laune

Reputation: 31290

Looking at

new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/...")

I see that you are trying to introduce a directory from variable title. Not sure whether this creates all missing directories. So please make sure that this directory exists and create it before writing to the file two levels below.

Upvotes: 4

Braj
Braj

Reputation: 46841

You can try any one based on file location. Just use prefix / to start looking into src folder.

// Read from resources folder parallel to src in your project
File file1 = new File("resources/abc.txt");
System.out.println(file1.getAbsolutePath());

// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());

Note: Try to avoid spaces in the path.

First check whether folder(directory) exists or not:

sample code:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}

Read more...

Upvotes: 1

new FileWriter will never create a directory. It will throw a FileNotFoundException if the directory doesn't exist.

To create the directory (and all parent directories that don't already exist), you can use something like this:

new File("src/opinarium3/media/presentaciones/"+title+"/comments/").mkdirs();

Upvotes: 5

Related Questions