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?

Thunderforge
  • 19,637
  • 18
  • 83
  • 130

2 Answers2

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.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • 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. – Thunderforge Feb 13 '13 at 01:53
  • 3
    even better, use `File.createTempFile()` and skip the system property altogether. – jtahlborn Feb 13 '13 at 01:54
  • 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. – Thunderforge Feb 13 '13 at 01:55
  • 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. – Kevin Day Feb 13 '13 at 04:35
-1

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • 2
    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.. – fvu Feb 13 '13 at 01:46