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

RT_ picture RT_ · Mar 7, 2012 · Viewed 64.2k times · Source

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

Answer

Marvin Pinto picture Marvin Pinto · Mar 7, 2012

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.