Permission Denied When Writing File to Default Temp Directory
Asked Answered
D

2

7

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?

Danyel answered 13/2, 2013 at 1:34 Comment(2)
sudo java <Class name> ??Masson
Not sure why there was a downvote and a vote to close... It was a legitimate question that wound up being due to a misunderstanding of code.Danyel
C
12

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.

Calorie answered 13/2, 2013 at 1:39 Comment(4)
Ah, so it looks like Mac OS X and Windows have a trailing /, but Linux does not. Using the two-parameter constructor does indeed provide a clean solution to the problem.Danyel
even better, use File.createTempFile() and skip the system property altogether.Rae
Thanks for that hint! There are still a few other places in the code where I do something similar, so I'll probably be using both together.Danyel
tip - if you use File.createTempFile(), make sure you have some mechanism for cleaning up behind yourself (and File.deleteOnClose() doesn't cut it). Use a prefix unique to your app and purge the temp directory of files with that prefix on launch - something like that.Kerf
S
-1

If you have permission to you could change the permissions on the directory using chmod.

Sequestered answered 13/2, 2013 at 1:35 Comment(1)
If the directory pointed to by java.io.tmpdir needs permission tweaking I'd rather say there's something horribly wrong with the Linux installation..Calorie

© 2022 - 2024 — McMap. All rights reserved.