Skip to content
Advertisement

Java output: can’t write to subdirectory

How can I write to a file in a subfolder? Other answers on here said to use Paths, but no luck. In my code, for whichFileToSaveTo, if I remove “/Subfolder/” from it, my code works correctly and writes to the file. With “/Subfolder/”, I get a java.io.FileNotFoundException.

I am using Windows 10. Thank you!

/* whichFileToSaveTo = "/Subfolder/defaultSave.txt" */
FileWriter fw1 = new FileWriter(Paths.get(whichFileToSaveTo).toFile());    
for (JTextField j : times_JTextField_Array) {
    fw1.write(j.getText() + "n");
}
fw1.close();

Advertisement

Answer

Solved. The solution was to use absolute path:

FileWriter fw1=new FileWriter(Paths.get("").toAbsolutePath() + whichFileToSaveTo);

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement