如何在createTempFile中更改默认名称?

时间:2015-02-05 00:57:14

标签: java

这是我正在使用的代码:

import java.io.File;
import java.io.IOException;
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();

        }

    }
}

我得到了这个结果: C:\用户\ mkyong \应用程序数据\本地\ TEMP \临时文件名称的 79456440 的.tmp

是否可以在没有附加名称的情况下保存结果? (示例,C:\Users\mkyong\AppData\Local\Temp\temp-file-name.tmp)谢谢!

3 个答案:

答案 0 :(得分:1)

问:如何更改createTempFile中的默认名称?

答案:
你不能。

如果可以,您可以使createTempFile的保证无效,根据the javadoc,保证:

  1. 返回的抽象路径名表示的文件不存在 在调用此方法之前,
  2. 这种方法都不是 它的变体将在。中再次返回相同的抽象路径名 当前调用虚拟机。
  3. 如果您关心文件名,则createTempFile()可能不是创建文件的合适方式。

    可以 找出系统临时文件目录是什么,并在那里创建自己的文件,如@MadcoreTom所示,但您必须管理文件名的可能性碰撞自己。

    使用createTempFile的另一种策略取决于您使用该文件的内容以及您关注它的名称的原因,您没有说明。

答案 1 :(得分:0)

我认为createTempFile的想法是创建一个唯一的文件名。它使用数字来确保它是唯一的。每次创建临时文件时,保证(?)都没有现有的同名文件。

您也可以使用temp.getParentFile()代替substring&你正在使用的绝对路径。

如果您只使用Windows,则可以使用类似这样的内容来获取环境变量(与%temp%中的cmd相同)

String tempDir = new File(System.getenv("temp")).getAbsolutePath()

答案 2 :(得分:0)

使用此

public class GetTempFilePathExample {
public static void main(String[] args) {
    try {
        // create a temp file
        // File temp = File.createTempFile("temp-file-name", ".tmp");
        String folderLocation = System.getenv("temp");
        String fileName = "aa.tmp";
        File temp = new File(folderLocation + File.separator + fileName);
        if (temp.createNewFile()) {
            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 (Exception e) {
        e.printStackTrace();

    }

}