Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating temp Folder in java

Tags:

java

macos

I need to create a temp folder where I can put some temp files for processing. I am not sure if I would have Read/Write access in the folder where my application jar would be executed.

  1. Is it best to create the temp folder in the System's temp Directory ?
  2. When I use the File tempFolder = File.createTempFile("fooo",""); Where is the folder created ? When I cd into the temp folder in my mac I am not able to see a folder by name fooo.
like image 912
yesh Avatar asked Oct 25 '12 12:10

yesh


People also ask

How do I create a temp folder?

Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though. Save this answer.

Can we create a folder in Java?

In Java, we can use the File object to create a new folder or directory. The File class of Java provide a way through which we can make or create a directory or folder. We use the mkdir() method of the File class to create a new folder.

How do I find the Java temp folder?

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


1 Answers

You are almost done with create tempfolder, see this:

import java.io.File;
import java.io.IOException;

public class TempFolder {
    public static void main(String[] args) throws IOException {
        File file = File.createTempFile("my_prefix", "");
        System.out.println(file.getAbsolutePath() + " isFile: " + file.isFile() + " isDir:" + file.isDirectory());
        file.delete();
        file.mkdir();
        System.out.println(file.getAbsolutePath() + " isFile: " + file.isFile() + " isDir:" + file.isDirectory());
    }
}

first createTempFile will make a real file for you, just remove it and make a directory using the same name.

I use osx, too. My result is:

/var/folders/aQ/aQLNlFLOF28xewK2A7i0X++++TM/-Tmp-/my_prefix8720723534029791962 isFile: true isDir:false
/var/folders/aQ/aQLNlFLOF28xewK2A7i0X++++TM/-Tmp-/my_prefix8720723534029791962 isFile: false isDir:true
like image 73
qrtt1 Avatar answered Sep 28 '22 06:09

qrtt1