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();
}
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With