Creating a temporary file and directory in Java

Posted on 15-01-2013 14:08 by graham
This tutorial shows how to create a temporary file and a temporary directory in Java.

Temporary file


Creating a temporary file is quite easy:
File tmpFile = File.createTempFile("tmp", Long.toString(System.nanoTime()));

Temporary directory


Creating a temporary directory is a bit more tricky. There is no method that does that, so what we do is create a temporary file to get a path and a random name for a temporary resource, then we delete the file and create a directory with the same name:
File tmpDir = File.createTempFile("tmp", Long.toString(System.nanoTime()));
tmpDir.delete();
tmpDir.mkdir();
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems