java 将文件写入默认临时目录时权限被拒绝

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14845045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:36:10  来源:igfitidea点击:

Permission Denied When Writing File to Default Temp Directory

javalinuxtempdir

提问by Thunderforge

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:

我的程序做了一些相当密集的操作,所以我使用了一个临时文件来加快速度。我使用以下 Java 代码:

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.

此代码在 Mac OS X 和 Windows 上运行良好。它在 Java 临时目录中创建一个暂存文件,该目录由操作系统决定。

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

但是,当我在 Linux(特别是 Linux Mint)上尝试这个程序时,我在“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?

我真的对这个错误感到困惑,因为我认为该System.getProperty("java.io.tempdir")方法收集的临时目录将是用户可以写入的目录(并且它在其他操作系统上)。在 Linux 上不是这样吗?有什么方法可以授予对临时目录的访问权限吗?我应该使用其他目录吗?

回答by fvu

On Linux java.io.tmpdiris 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

在 Linuxjava.io.tmpdir上通常设置为/tmp(注意缺少尾随 /)。与其使用额外的嵌入斜杠,不如使用两个参数的 File 构造函数更干净

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

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

这样你就不必担心尾随斜杠与否。

回答by Kevin Bowersox

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

如果您有权限,您可以使用chmod.