How to get the temporary file path in Java
In Java, we can use System.getProperty("java.io.tmpdir")
to get the default temporary file location.
- For Windows, the default temporary folder is
%USER%\AppData\Local\Temp
- For Linux, the default temporary folder is
/tmp
1. java.io.tmpdir
Run the below Java program on a Ubuntu Linux.
TempFilePath1
package com.mkyong.io.temp;
public class TempFilePath1 {
public static void main(String[] args) {
String tmpdir = System.getProperty("java.io.tmpdir");
System.out.println("Temp file path: " + tmpdir);
}
}
Output
Temp file path: /tmp
2. Create Temporary File
Alternatively, we can create a temporary file and substring
the file path to get the temporary file location.
2.1 Java NIO example.
TempFilePath2.java
package com.mkyong.io.temp;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class TempFilePath2 {
public static void main(String[] args) {
// Java NIO
try {
Path temp = Files.createTempFile("", ".tmp");
String absolutePath = temp.toString();
System.out.println("Temp file : " + absolutePath);
String separator = FileSystems.getDefault().getSeparator();
String tempFilePath = absolutePath
.substring(0, absolutePath.lastIndexOf(separator));
System.out.println("Temp file path : " + tempFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Temp file : /tmp/log_11536339146653799756.tmp
Temp file path : /tmp
2.2 Java IO example.
TempFilePath3.java
package com.mkyong.io.temp;
import java.io.File;
import java.io.IOException;
public class TempFilePath3 {
public static void main(String[] args) {
// Java IO
try {
File temp = File.createTempFile("log_", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
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();
}
}
}
Output
Temp file : /tmp/log_9219838414378386507.tmp
Temp file path : /tmp
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Why do we need both normal file and temporaray file?. What is the advantage of creating a temporary files ?
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());
}
You can just do the following:
How to display that temp file?
how to get path of folder by mouse double click on that folder
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);
but above one is not working