有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java系统在createTempFile时找不到路径

我在调用java函数createTempFile("test", "test")时遇到一个异常,它说“系统找不到指定的路径”。 尝试过谷歌搜索,但没有成功。 有人知道java从何处获得其默认临时路径以及如何找不到它吗? Windows变量似乎是正确的,更改它们不会影响java


共 (3) 个答案

  1. # 1 楼答案

    试试看:

    String path = System.getProperty("java.io.tmpdir");
    

    请参阅:get property method

    为了完整起见,这里还添加了Java的file类中的createTempFile(String prefix,String suffix)createTempFile(String prefix, String suffix, File directory)方法

    这是我的代码,可以找到临时文件的路径并找到临时路径:

    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
    
  2. # 2 楼答案

    Does anyone know from where java gets its default temp path

    它是从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为空,则将其设置为tmpdir,声明如下:

    private static final Path tmpdir =
        Paths.get(doPrivileged(new GetPropertyAction("java.io.tmpdir")));
    

    您可以按照@Joni的答案显式设置属性。如果没有显式设置,JVM会在启动时将其初始化为特定于平台的默认值——另请参见Environment variable to control java.io.tmpdir?

    and how can it be not found?

    如果属性java.io.tmpdir指向无效目录,则无法创建临时文件

  3. # 3 楼答案

    无论默认值是如何获得的,您都可以在启动JVM时通过设置系统属性java.io.tmpdir来设置临时文件目录:

    java -Djava.io.tmpdir=/path/to/where/ever/you/like YourClass
    

    如果想知道默认值的来源,必须阅读JVM的源代码。例如,Windows上的OpenJDK调用API函数^{}(在JDK源代码中搜索文件java_props_md.c),该函数通过以下方式在环境变量和注册表中查找路径:

    The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

    1. The path specified by the TMP environment variable.
    2. The path specified by the TEMP environment variable.
    3. The path specified by the USERPROFILE environment variable.
    4. The Windows directory.

    Note that the function does not verify that the path exists, nor does it test to see if the current process has any kind of access rights to the path.