How to create a temp file in java without the random number appended to the filename?

JavaTemporary Files

Java Problem Overview


I need to create a temp file, so I tried this:

String[] TempFiles = {"c1234c10","c1234c11","c1234c12","c1234c13"};
for (int i = 0; i <= 3; i++) {
    try {
        String tempFile = TempFiles[i]; 
        File temp = File.createTempFile(tempFile, ".xls"); 
        System.out.println("Temp file : " + temp.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The output is something like this:

 Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c108415816200650069233.xls
 Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c113748833645638701089.xls
 Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c126104766829220422260.xls
 Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c137493179265536640669.xls

Now, I don't want the extra numbers (long int) which is getting added to the file name. How can I achieve that? Thanks

Java Solutions


Solution 1 - Java

First, use the following snippet to get the system's temp directory:

String tDir = System.getProperty("java.io.tmpdir");

Then use the tDir variable in conjunction with your tempFiles[] array to create each file individually.

Solution 2 - Java

Using [Guava][1]:

import com.google.common.io.Files;

...

File myTempFile = new File(Files.createTempDir(), "MySpecificName.png");

[1]: https://github.com/google/guava "Guava"

Solution 3 - Java

You can't if you use File.createTempFile to generate a temporary file name. I looked at the java source for generating a temp file (for java 1.7, you didn't state your version so I just used mine):

private static class TempDirectory {
    private TempDirectory() { }

    // temporary directory location
    private static final File tmpdir = new File(fs.normalize(AccessController
        .doPrivileged(new GetPropertyAction("java.io.tmpdir"))));
    static File location() {
        return tmpdir;
    }

    // file name generation
    private static final SecureRandom random = new SecureRandom();
    static File generateFile(String prefix, String suffix, File dir) {
        long n = random.nextLong();
        if (n == Long.MIN_VALUE) {
            n = 0;      // corner case
        } else {
            n = Math.abs(n);
        }
        return new File(dir, prefix + Long.toString(n) + suffix);
    }
}

This is the code in the java JDK that generates the temp file name. You can see that it generates a random number and inserts it into your file name between your prefix and suffix. This is in "File.java" (in java.io). I did not see any way to change that.

Solution 4 - Java

If you want files with specific names created in the system-wide temporary directory, then expand the %temp% environment variable and create the file manually, nothing wrong with that.

Edit: Actually, use System.getProperty("java.io.tmpdir")); for that.

Solution 5 - Java

You can create a temp directory then store new files in it. This way all of the new files you add won't have a random extension to it. When you're done all you have to do is delete the temp directory you added.

public static File createTempFile(String prefix, String suffix) {		
	File parent = new File(System.getProperty("java.io.tmpdir"));	
	
	File temp = new File(parent, prefix + suffix);
	
	if (temp.exists()) {
		temp.delete();
	}
	
	try {
		temp.createNewFile();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
	
	return temp;
}


public static File createTempDirectory(String fileName) {		
	File parent = new File(System.getProperty("java.io.tmpdir"));	
	
	File temp = new File(parent, fileName);
	
	if (temp.exists()) {
		temp.delete();
	}
	
	temp.mkdir();
	
	return temp;
}

Solution 6 - Java

Just putting up the option here: If someone anyhow need to use createTempFile method, you can do create a temp file and rename it using Files.move option:

final Path path = Files.createTempFile(fileName, ".xls");
Files.move(path, path.resolveSibling(fileName));

Solution 7 - Java

Custom names can be saved as follows

File temp=new File(tempFile, ".xls");
if (!temp.exists()) {
	temp.createNewFile();
}

Solution 8 - Java

public static File createTempDirectory(String dirName) {
        File baseDir = new File(System.getProperty("java.io.tmpdir"));
        File tempDir = new File(baseDir, dirName);
        if (tempDir.mkdir()) {
          return tempDir;
        }
        return null;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRT_View Question on Stackoverflow
Solution 1 - JavaMarvin PintoView Answer on Stackoverflow
Solution 2 - JavaBrad JohnsonView Answer on Stackoverflow
Solution 3 - JavajmqView Answer on Stackoverflow
Solution 4 - JavaIrfyView Answer on Stackoverflow
Solution 5 - Javauser6186835View Answer on Stackoverflow
Solution 6 - JavaBhisham UdasiView Answer on Stackoverflow
Solution 7 - JavaJunaid MalikView Answer on Stackoverflow
Solution 8 - JavaAmbikesh Kumar ShuklaView Answer on Stackoverflow