在调用java函数createTempFile("test", "test")
时,我得到一个异常,说“系统无法找到指定的路径”。
尝试使用谷歌搜索,但没有运气。
有谁知道java获取其默认临时路径的位置以及如何找不到它?
Windows变量似乎是正确的,更改它们不会影响java。
答案 0 :(得分:15)
有没有人知道java获取默认临时路径的位置
从java.io.tmpdir
属性中读取。
Files.createTempFile("test", "test");
基本上调用java.nio.file.TempFileHelper.createTempFile(null, prefix, suffix, attrs);
,再次调用java.nio.file.TempFileHelper.create(dir, prefix, suffix, false, attrs);
。在那里,如果dir
为null,则将其设置为tmpdir
,其声明如下:
private static final Path tmpdir =
Paths.get(doPrivileged(new GetPropertyAction("java.io.tmpdir")));
您可以显式设置属性,如@Joni的答案所示。如果您未明确设置它,JVM会在启动时将其初始化为特定于平台的默认值 - 另请参阅Environment variable to control java.io.tmpdir?
如何找不到?
如果属性java.io.tmpdir
指向无效目录,则无法创建临时文件。
答案 1 :(得分:7)
无论如何获取默认值,您都可以通过在启动JVM时设置系统属性java.io.tmpdir
来设置临时文件目录:
java -Djava.io.tmpdir=/path/to/where/ever/you/like YourClass
如果您想知道默认值的来源,您必须阅读JVM的源代码。例如,Windows上的OpenJDK调用API函数GetTempPathW
(在JDK源代码中搜索文件java_props_md.c
),它以下列方式查找环境变量和注册表中的路径:
GetTempPath
函数按以下顺序检查环境变量的存在,并使用找到的第一个路径:
- TMP环境变量指定的路径。
- TEMP环境变量指定的路径。
- USERPROFILE环境变量指定的路径。
- Windows目录。
醇>请注意,该函数不会验证路径是否存在,也不会测试当前进程是否对路径具有任何类型的访问权限。
答案 2 :(得分:3)
尝试:
String path = System.getProperty("java.io.tmpdir");
请参阅: get property method
为了完整起见,在这里添加它,还有来自Java的强 createTempFile(String prefix,String suffix) 和 createTempFile(String prefix, String suffix, File directory) 方法 {{3 } 类。
以下是我的代码来查找临时文件的路径并查找临时路径:
public class GetTempFilePathExample
{
public static void main(String[] args)
{
try{
//create a temp file
File temp = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
//Get tempropary file path
String absolutePath = temp.getAbsolutePath();
String tempFilePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("Temp file path : " + tempFilePath);
}catch(IOException e){
e.printStackTrace();
}
}
}
此代码的输出为:
Temp file : /tmp/temp-file-name3697762749201044262.tmp
Temp file path : /tmp