How to create a temp file in java without the random number appended to the filename?
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.
Using Guava:
import com.google.common.io.Files;
...
File myTempFile = new File(Files.createTempDir(), "MySpecificName.png");
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.
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.
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;
}