Java Temp File Create getTempFile(File file)

Here you can find the source of getTempFile(File file)

Description

create a empty temp file at file's directory, temp file's name is based on file's name, i.e.

License

Open Source License

Declaration

public static File getTempFile(File file) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import java.util.Random;

public class Main {
    private static final Random FILENAME_RANDOM = new Random();

    /**/*from   ww w .  j  a va  2s.  com*/
     * create a empty temp file at file's directory, temp file's name is based on file's name, i.e.
     * input "f1.txt", may output "f1.txt.tmp.467913456"
     */
    public static File getTempFile(File file) throws IOException {
        File tempFile;
        while (true) {
            tempFile = new File(file.getParent(), file.getName() + ".tmp." + FILENAME_RANDOM.nextInt());
            if (!tempFile.exists()) {
                if (!tempFile.createNewFile()) {
                    throw new IOException(String.format("create %s failed", tempFile));
                }
                return tempFile;
            } else
                continue;
        }
    }
}

Related

  1. createTempFile(@Nonnull String prefix, @Nonnull String suffix, @Nullable File parentDir)
  2. createTempFile(final String file, final String ext)
  3. createTempFile(String oriFileName)
  4. getTempFile()
  5. getTempFile()
  6. getTempFile(File parent, String fileName)
  7. getTempFile(final File stackFile)
  8. getTempFile(final String directory, final String suffix, boolean autodelete)
  9. getTempFile(final String name)