简体   繁体   中英

how to create a temporary directory inside a Java application using java 1.6 ?

I have a java application where i'm using javaMail API to send attachments generated by other utilities java class. IS there any way to create a temporary folder where to save these attachments before sending it using java 1.6 version ?

You can use File.createTempFile to create temp files which go to a temp directory (depending on your platform), but there's no way to create a temp dir in a similar way.

You should modify your generating code to create temp files instead, and then pass the File objects around.

Google Guava has a Files.createTempDir() method, explained here .

  /** Maximum loop count when creating temp directories. */
  private static final int TEMP_DIR_ATTEMPTS = 10000;

public static File createTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    String baseName = System.currentTimeMillis() + "-";

    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
        File tempDir = new File(baseDir, baseName + counter);
        if (tempDir.mkdir()) {
            return tempDir;
        }
    }
    throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
}

The standard way is to create a temp file, then delete it, then recreate it as a directory. For example, this is how JUnit's TemporaryFolder Rule does it:

    File folder= File.createTempFile("junit", "");
    folder.delete();
    folder.mkdir();

However, this isn't threadsafe since something else can create the same file in the time between the delete() and mkdir() calls which will cause this code to fail.

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