0

I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:

f = File.createTempFile("tmp", ".txt", new File("D:/"));

This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
priya23
  • 21
  • 4

3 Answers3

4

In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.

You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
3

If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.

Also have a look at this post which shows a very simple way to create files.

Taken the post mentioned above:

String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs(); 
f.createNewFile();
Community
  • 1
  • 1
anirudh
  • 4,116
  • 2
  • 20
  • 35
  • I don't think it's good practice to use `File.separator` in this way. It can cause problems with portability (specifically, a class that is compiled on one OS will have File.separator inlined as that OS's value, so it may not work as expected when run on a different OS). It is better to use `new File(dirName, childName)` which always works. In your case, `new File(new File("C:", "hello"), "hi.txt");`. Not sure about `new File("C:")`, I've never tried that (not a regular user of Windows). – Paul Hicks Apr 21 '14 at 08:05
1

try regex

fileName = fileName.replaceAll("\\d", "");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275