Javaで一時ファイルパスを取得する方法

Javaで一時ファイルパスを取得する方法

Javaで一時ファイルパスを取得する例を次に示します。

package com.example.file;

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();

        }

    }
}

結果

Temp file : C:\Users\example\AppData\Local\Temp\temp-file-name79456440.tmp
Temp file path : C:\Users\example\AppData\Local\Temp