将文件写入默认临时目录时,权限被拒绝 [英] Permission Denied When Writing File to Default Temp Directory
问题描述
我的程序做了一些相当繁琐的操作,因此我使用了一个暂存文件来加快处理速度.我使用以下Java代码:
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();
此代码在Mac OS X和Windows上可以正常工作.它将在Java临时目录中创建一个临时文件,该文件由操作系统确定.
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.
但是,当我在Linux(特别是Linux Mint)上尝试该程序时,在"scratchFile.createNewFile()"行上出现以下错误
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
这个错误让我很困惑,因为我发现System.getProperty("java.io.tempdir")
方法收集的temp目录将是用户可以写入的目录(并且在其他操作系统上).在Linux上不是这样吗?有什么方法可以授予对temp目录的访问权限?我应该使用其他目录吗?
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?
推荐答案
在Linux上,java.io.tmpdir
通常设置为/tmp
(请注意缺少尾部的/).使用
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.
这篇关于将文件写入默认临时目录时,权限被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!