Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 913
RT_ Avatar asked Mar 07 '12 02:03

RT_


People also ask

How do you create a temp file in Java without the random number appended to the file?

Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.

What is temporary path in Java?

tmpdir") to get the default temporary file location. For Windows, the default temporary folder is %USER%\AppData\Local\Temp. For Linux, the default temporary folder is /tmp.


2 Answers

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.

like image 153
Marvin Pinto Avatar answered Sep 23 '22 01:09

Marvin Pinto


Using Guava:

import com.google.common.io.Files;  ...  File myTempFile = new File(Files.createTempDir(), "MySpecificName.png"); 
like image 30
Brad Johnson Avatar answered Sep 19 '22 01:09

Brad Johnson