Как создать временный каталог/папку в Java?

Пожалуйста, внимательно изучите этот пример, он ответит на все ваши вопросы, и вы увидите, где вы идете не так: call-feature.feature

Например, чтобы получить [112 ] из результата call вы должны его «распаковать»:

Scenario: create kittens
    * def result = call read('create-two-cats.feature')
    * def temp = result.response

338
задан Sled 27 July 2016 в 07:55
поделиться

7 ответов

Если Вы используете использование JDK 7 новое класс Files.createTempDirectory для создания временного каталога.

Path tempDirWithPrefix = Files.createTempDirectory(prefix);

Перед JDK 7 это должно сделать это:

public static File createTempDirectory()
    throws IOException
{
    final File temp;

    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

    if(!(temp.delete()))
    {
        throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
    }

    if(!(temp.mkdir()))
    {
        throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
    }

    return (temp);
}

Вы могли сделать лучшие исключения (разделите IOException на подклассы), если Вы хотите.

364
ответ дан GreenGiant 23 November 2019 в 00:39
поделиться

Используя File#createTempFile и delete для создания уникального имени для каталога кажется хорошо. Необходимо добавить ShutdownHook для удаления каталога (рекурсивно) на завершении работы JVM.

0
ответ дан ordnungswidrig 23 November 2019 в 00:39
поделиться

Этот код должен работать обоснованно хорошо:

public static File createTempDir() {
    final String baseTempPath = System.getProperty("java.io.tmpdir");

    Random rand = new Random();
    int randomInt = 1 + rand.nextInt();

    File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
    if (tempDir.exists() == false) {
        tempDir.mkdir();
    }

    tempDir.deleteOnExit();

    return tempDir;
}
3
ответ дан matt b 23 November 2019 в 00:39
поделиться

Как обсуждено в этот RFE и его комментарии, Вы могли звонить tempDir.delete() сначала. Или Вы могли использовать System.getProperty("java.io.tmpdir") и создать каталог там. Так или иначе необходимо не забыть звонить tempDir.deleteOnExit(), или файл не будет удален после того, как Вы будете сделаны.

3
ответ дан Michael Myers 23 November 2019 в 00:39
поделиться

Ну, "createTempFile" на самом деле создает файл. Итак, почему не просто удаляют его сначала и затем делают mkdir на нем?

5
ответ дан Paul Tomblin 23 November 2019 в 00:39
поделиться

This is what I decided to do for my own code:

/**
 * Create a new temporary directory. Use something like
 * {@link #recursiveDelete(File)} to clean this directory up since it isn't
 * deleted automatically
 * @return  the new directory
 * @throws IOException if there is an error creating the temporary directory
 */
public static File createTempDir() throws IOException
{
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do
    {
        attemptCount++;
        if(attemptCount > maxAttempts)
        {
            throw new IOException(
                    "The highly improbable has occurred! Failed to " +
                    "create a unique temporary directory after " +
                    maxAttempts + " attempts.");
        }
        String dirName = UUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while(newTempDir.exists());

    if(newTempDir.mkdirs())
    {
        return newTempDir;
    }
    else
    {
        throw new IOException(
                "Failed to create temp dir named " +
                newTempDir.getAbsolutePath());
    }
}

/**
 * Recursively delete file or directory
 * @param fileOrDir
 *          the file or dir to delete
 * @return
 *          true iff all files are successfully deleted
 */
public static boolean recursiveDelete(File fileOrDir)
{
    if(fileOrDir.isDirectory())
    {
        // recursively delete contents
        for(File innerFile: fileOrDir.listFiles())
        {
            if(!FileUtilities.recursiveDelete(innerFile))
            {
                return false;
            }
        }
    }

    return fileOrDir.delete();
}
14
ответ дан 23 November 2019 в 00:39
поделиться

Не используйте deleteOnExit () , даже если вы явно удалите его позже.

Google 'deleteonexit is evil' для получения дополнительной информации, но суть проблема заключается в следующем:

  1. deleteOnExit () удаляет только при нормальном завершении работы JVM, но не приводит к сбою или прекращению работы процесса JVM.

  2. deleteOnExit () удаляет только при завершении работы JVM - не подходит для длительных серверных процессов потому что:

  3. Самый злой из всех - deleteOnExit () потребляет память для каждой записи временного файла. Если ваш процесс работает в течение нескольких месяцев или создает много временных файлов за короткое время, вы потребляете память и никогда не освобождаете ее, пока JVM не выключится.

25
ответ дан 23 November 2019 в 00:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: