Java Temp Directory Create createTempDirectory()

Here you can find the source of createTempDirectory()

Description

Creates a new temp directory in the java temp folder.

License

Open Source License

Return

the path to the new directory.

Declaration

public static Path createTempDirectory() 

Method Source Code

//package com.java2s;
/**/*from w  w w .  j av a2 s  .c om*/
 * Copyright (c) 2016 NumberFour AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   NumberFour AG - Initial API and implementation
 */

import static com.google.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    /**
     * Creates a new temp directory in the java temp folder. The newly created folder will be deleted on graceful VM
     * shutdown.
     *
     * @return the path to the new directory.
     */
    public static Path createTempDirectory() {
        final File parent = new File(getTempDirValue());
        if (!parent.exists() || !parent.canWrite()) {
            throw new RuntimeException("Cannot access temporary directory under: " + getTempDirValue());
        }
        File child;
        try {
            child = Files.createTempDirectory(parent.toPath(), null).toFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (!child.exists()) {
            throw new RuntimeException("Error while trying to create folder at " + parent + ".");
        }
        child.deleteOnExit();
        return child.toPath();
    }

    /**
     * Returns with the value of {@code System.getProperty("java.io.tmpdir")}. Never {@code null}.
     */
    private static final String getTempDirValue() {
        return checkNotNull(System.getProperty("java.io.tmpdir"), "Null for java.io.tmpdir system property.");
    }
}

Related

  1. createTempDir()
  2. createTempDir(final String prefix)
  3. createTempDir(String prefix)
  4. createTempDir(String subdirectory)
  5. createTempDir(String suffix)
  6. createTempDirectory()
  7. createTempDirectory()
  8. createTempDirectory(File parent, String prefix)
  9. createTempDirectory(String prefix)