I recently migrated a tomcat application from one Linux server to another. Since then, I am facing a new file creation issue on the new server. In the new server, when I try to create a file it fails, which works fine in the old server:
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile(); //this FAILS
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
To investigate the issue, I printed the working directory using:
String cwd = new File("").getAbsolutePath();
System.out.println(cwd);
And this debugging revealed the root cause behind the issue: The old server returned: var/lib/tomcat, whereas the new server returned: / (the root directory) As the tomcat user did not (and should not) have write permission on root directory, it failed to create the file.
My question, which factor decides the current working directory of Tomcat, and how to configure it?
Here are my Tomcat and java environment variables.
Environment="JAVA_HOME=/usr/lib/jvm/jre"
Environment="JAVA_OPTS=-Djava.security.egd=file:///dev/urandom"
Environment="CATALINA_BASE=/opt/tomcat"
Environment="CATALINA_HOME=/opt/tomcat"
Update: I tried -Duser.dir
to configure the working directory. After using this, I get expected result from System.out.println(cwd);
. But the issue still persists, the file creation fails. apparently, this does not work for FileOutputStreams
.
Source: Changing the current working directory in Java?
The ownership and permissions are handled properly. I am looking for a system-side solution without making any code change, as the same code is working in the old server.