Creating a temporary file and directory

The post shows you how to create a temporary file and directory in java with an example.

Main Code


1  package nio;
2  
3  import java.io.IOException;
4  import java.nio.file.Files;
5  import java.nio.file.Path;
6  import java.nio.file.Paths;
7  
8  public class Example1 {
9   public static void main(String[] args) throws IOException {
10      Path path = Files.createTempFile("prefix", "suffix");
11      System.out.println(path.getFileName());
12      
13      Path path1 = Paths.get("E:\\Theme");
14      path = Files.createTempFile(path1, "prefix", "suffix");
15      System.out.println(path.toString());
16      
17      path = Files.createTempDirectory("prefix");
18      System.out.println(path.getFileName());
19      
20      path = Files.createTempDirectory(path1, "prefix");
21      System.out.println(path.toString());
22  }
23 }

Explanation

At line 10, we call static method createTempFile of Files class. The method takes three arguments which are
1) A string which will be used as prefix in the file name of the temporary file
2) A string which will be used as suffix in the file name of the temporary file
3) A set of file attributes, this is optional.

The method will create a file at the default temporary directory location.

Another way is calling overloaded version of createTempFile of Files class. This method in addition to the three arguments mentioned above, it takes fourth arguement which is a Path variable. We can use this method to create temporary file in the specified directory.

At line 14, we call the createTempFile to create a temporary file in directory E:\Theme.

Similar to createTempFile method, there is createTempDirectory method. The only difference between these two methods is that createTempDirectory doesn’t take a String which will
act as suffix in the directory name.

At line 17, we are create a temmporary directory at the default temporary directory location.

At line 20, we are creating a temporary directory at the location E:\Theme folder.

Output

Temporary file name: prefix8048643457547564372suffix
Temporary file location: E:\Theme\prefix1342333585434128681suffix
Temporary directory name: prefix11499294723424623
Temporary directory location: E:\Theme\prefix2625526680709542290

Leave a Reply