I am trying to write something to a file, like this:
FileWriter fw = new FileWriter("somefile.txt", true);
It works correctly when started by a single process. Like this:
java -jar XXXXXXX.jar
But when calling it by another process, an IOException will be thrown. Example:
java.io.FileNotFoundException: 'somefile.txt' (No such file or directory)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:192)
at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
at java.io.FileWriter.<init>(FileWriter.java:61)
A number of answers have incorrectly suggested that your exception is occurring because the file doesn't exist. That is not the reason; the documentation for the constructor clearly states:
- Throws:
- IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you are passing a relative file name (a string with no '/' or '\' in it), it refers to a file in the current directory. I'm guessing that when you run it using java -jar
, your current directory is a directory for which you have write permission, but when that other process runs it, the current directory is not writable.
In the past, older Java versions had the habit of throwing FileNotFoundException when trying to write in an unwritable directory. The latest Java doesn't seem to do it, though, so I'm not certain if that's the problem. You can get a clearer exception by using the java.nio.file package instead:
Path path = Paths.get("somefile.txt");
Writer writer = Files.newBufferedWriter(path, Charset.defaultCharset(),
StandardOpenOption.APPEND, StandardOpenOption.CREATE);
There are several possible explanations:
somefile.txt
in the current directory.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