Permission Denied When Writing File to Default Temp Directory

Thunderforge picture Thunderforge · Feb 13, 2013 · Viewed 13.3k times · Source

My program does some fairly intensive operations, so I use a scratch file in order to speed things up. I use the following Java code:

File scratchFile = new File(System.getProperty("java.io.tmpdir") + "WCCTempFile.tmp");
if (!scratchFile.exists())
    scratchFile.createNewFile();

This code works just fine on Mac OS X and Windows. It creates a scratch file in the Java temporary directory, which is determined by the operating system.

However, when I try this program on Linux (specifically Linux Mint), I get the following error on the line "scratchFile.createNewFile()"

java.io.IOException: Permission Denied

I'm really confused by this error because I figured that the temp directory that is gathered by the System.getProperty("java.io.tempdir") method would be one that the user could write to (and it is on other operating systems). Is this not the case on Linux? Is there some way to grant access to the temp directory? Is there some other directory I'm supposed to be using?

Answer

fvu picture fvu · Feb 13, 2013

On Linux java.io.tmpdir is commonly set to /tmp (note the missing trailing /). Instead of messing around with extra embedded slashes, it's a lot cleaner to use the two-parameter File constructor

File scratchFile = new File(System.getProperty("java.io.tmpdir"),"WCCTempFile.tmp");

That way you don't have to worry about trailing slashes or not.