Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.FileNotFoundException when opening file with filewriter in Java

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)                       
like image 621
user2210901 Avatar asked Dec 11 '22 16:12

user2210901


2 Answers

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);
like image 176
VGR Avatar answered Jan 12 '23 22:01

VGR


There are several possible explanations:

  1. The process does not have permissions to create somefile.txt in the current directory.
  2. On some operating systems, it might not be possible to create/overwrite the file if it already exists and is in use by another process.
like image 38
NPE Avatar answered Jan 12 '23 22:01

NPE