In Java, we can use System.getProperty("java.io.tmpdir") to get the default temporary file location.

  1. For Windows, the default temporary folder is %USER%\AppData\Local\Temp
  2. For Linux, the default temporary folder is /tmp

1. java.io.tmpdir

Run the below Java program on a Ubuntu Linux.

TempFilePath1.java

package com.favtuts.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.favtuts.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.favtuts.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/favtuts/java-core-tutorials-examples

$ cd java-io/temp

References

Leave a Reply

Your email address will not be published. Required fields are marked *