Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 328
Alexis R Devitre Avatar asked Jan 10 '23 03:01

Alexis R Devitre


2 Answers

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();
like image 81
user253751 Avatar answered Jan 21 '23 15:01

user253751


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.

like image 30
laune Avatar answered Jan 21 '23 15:01

laune