How to get the temporary file path in Java

Here’s an example to get the temporary file path in Java.

Example


package com.mkyong.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();
    		
    	}
    	
    }
}

Result


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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
vikrant
Guest
vikrant

how to get path of folder by mouse double click on that folder

Rafa
Guest
Rafa

Small problem: If that code is being code too often, it will overflow the directory with files. Have found the next solution in the next blog:

public class Main {

public static void main(String args[]) {

String tmpDirProperty = “java.io.tmpdir”;

String tmpDir = System.getProperty(tmpDirProperty);

System.out.println(tmpDir);

}

}

http://developinjava.com/tips-and-tricks/getting-the-users-temp-directory/

scf
Guest
scf

public static void main(String[] args) throws IOException {
//if running w/o security manager
System.out.println(System.getProperty(“java.io.tmpdir”));

//if running with security manager
File f = File.createTempFile(“test”, null);
System.out.println(f.getParentFile().getAbsolutePath());
}

Nikita Menon
Guest
Nikita Menon

Why do we need both normal file and temporaray file?. What is the advantage of creating a temporary files ?

ashok
Guest
ashok

i am tring to display the created temp file as follows
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(mFile), contentType);

ashok
Guest
ashok

but above one is not working

ashok
Guest
ashok

How to display that temp file?

ashok
Guest
ashok

Nice example.How to display temp file?

Charl FOurie
Guest
Charl FOurie

You can just do the following:

import java.io.File;

public class Blah {

  public static void main(String[] args) {
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    System.out.println("Temp File Path: " + tempDir);
  }

}