简体   繁体   中英

Creating temp Folder in java

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.

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

You should use File.createTempFile() .

Where it gets created depends on your environment. Try printing out the full path of such a file if your are interested.

On my Mac (10.8.2) the system Java created a file in "/var/folders/qj/v2cqt0t91h1b4rzj1s0pc_780000gp/T/" just now.

When you call File tempFolder = File.createTempFile("fooo","") it will return a File object. You can then call

tempFolder.getAbsolutePath();

linked here

and this will give you the location. At a guess I would say it was in /tmp/ which you can get to in from the Finder

  • choose Go to Folder
  • from the Go menu type /tmp/

This will take you to folders that are hidden as well.

I know in windows you can type %temp% in the windows explorer address bar to take you to the temp directory. I am not sure if there is anything like this on OSX

Try printing out tempFolder.getAbsolutePath(). It should give you the path where this folder is created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM