FileNotFoundException (The system cannot find the path specified)
I get this exception:
java.io.FileNotFoundException: C:\...\filename.xml (The system cannot find the path specified)
using this code:
开发者_StackOverflow中文版FileWriter fileWriter = new FileWriter(new File(path + date + time "filename.xml"));
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data");
Path exists but directories for 'date' and 'time' need to be created. Application has full permissions on the directory.
Any ideas?
The problem is because I'm creating a subdirectory in which to write the files. So I currently have
C:\example\
and want to write my files inC:\example\<date>\<time>\<files>
You need to call File#mkdirs()
before writing.
File file = new File("C:/example/newdir/newdir/filename.ext");
file.mkdirs();
// ...
Do assume that the computer is right and you are wrong.
And, in that scenario, the directory to which you want to write does not exit (or does not have permissions to do so).
- check the current working dir
System.getProperty("user.dir")
- debug from there
Code works for me. (Need to add a writer.close()
for text to show up in the file.)
What worked for me: The folder where my project was present had a space in the name. I replacedthe space with a hyphen(-). Now, the relative path of the file does not have a space (%20). This change worked for me. Hope it helps someone.
You also need to convert newly created file and folder paths to string.
File folder = new File("src\\main\\json\\", idNumber);
folder.mkdir();
if (!folder.exists()) {
try {
folder.createNewFile();
} catch (IOException ex) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex);
}
}
...
...
FileOutputStream output = null;
File file;
String content = data.toString();
try {
String folder_location = folder.toString() + "\\";
String filename = "CurrentInfo";
file = new File(folder_location + filename.toString() + ".json");
output = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] content_in_bytes = content.getBytes();
output.write(content_in_bytes);
output.flush();
output.close();
} catch (IOException ex) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, e);
}
}
}
精彩评论