Java temp directory windows

Working With Temporary Files/Folders in Java

Join the DZone community and get the full member experience.

The Java NIO.2 API provides support for working with temporary folders/files. For example, we can easily locate the default location for temporary folders/files as follows:

String defaultBaseDir = System.getProperty("java.io.tmpdir");

Commonly, in Windows, the default temporary folder is C:\Temp , %Windows%\Temp , or a temporary directory per user in Local Settings\Temp (this location is usually controlled via the TEMP environment variable).

Читайте также:  Проверить содержит ли ваша строка подстроку java используем метод string contains

In Linux/Unix, the global temporary directories are /tmp and /var/tmp . The preceding line of code will return the default location, depending on the operating system. Next, we’ll learn how to create a temporary folder/file.

Creating a Temporary Folder/File

Creating a temporary folder can be accomplished using:

This is a static method in the Files class that can be used as follows:

// C:\Users\Anghel\AppData\Local\Temp\8083202661590940905
Path tmpNoPrefix = Files.createTempDirectory(null);
// C:\Users\Anghel\AppData\Local\Temp\logs_5825861687219258744
String customDirPrefix = "logs_";
Path tmpCustomPrefix = Files.createTempDirectory(customDirPrefix);
// D:\tmp\logs_10153083118282372419
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
Path tmpCustomLocationAndPrefix = Files.createTempDirectory(customBaseDir, customDirPrefix);

Creating a temporary file can be accomplished via:

This is a static method in the Files class that can be used as follows:

// C:\Users\Anghel\AppData\Local\Temp\16106384687161465188.tmp
Path tmpNoPrefixSuffix = Files.createTempFile(null, null);
// C:\Users\Anghel\AppData\Local\Temp\log_402507375350226.txt
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomPrefixAndSuffix = Files.createTempFile(customFilePrefix, customFileSuffix);
// D:\tmp\log_13299365648984256372.txt
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomLocationPrefixSuffix 
 = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix);

Next, we’ll take a look at the different ways we can delete a temporary folder/file.

Deleting a Temporary Folder/File Via Shutdown-Hook

Deleting a temporary folder/file is a task that can be accomplished by the operating system or specialized tools. However, sometimes, we need to control this programmatically and delete a folder/file based on different design considerations.

A solution to this problem relies on the shutdown-hook mechanism, which can be implemented via the Runtime.getRuntime().addShutdownHook() method. This mechanism is useful whenever we need to complete certain tasks (for example, cleanup tasks) right before the JVM shuts down. It is implemented as a Java thread whose run() method is invoked when the shutdown-hook is executed by JVM at shut down. This is shown in the following code:

Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
 Path tmpDir = Files.createTempDirectory(customBaseDir, customDirPrefix);
 Path tmpFile1 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
 Path tmpFile2 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
 Runtime.getRuntime().addShutdownHook(new Thread() 
 try (DirectoryStreamPath> ds = Files.newDirectoryStream(tmpDir)) 
 //simulate some operations with temp file until delete it
> catch (IOException | InterruptedException e) 

A shutdown-hook will not be executed in the case of abnormal/forced terminations (for example, JVM crashes, Terminal operations are triggered, and so on). It runs when all the threads finish or when System.exit(0) is called. It is advisable to run it fast since they can be forcibly stopped before completion if something goes wrong (for example, the OS shuts down). Programmatically, a shutdown-hook can only be stopped by Runtime.halt() .

Deleting a Temporary Folder/File via deleteOnExit()

Another solution for deleting a temporary folder/file relies on the File.deleteOnExit() method. By calling this method, we can register for the deletion of a folder/file. The deletion action happens when JVM shuts down:

Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
 Path tmpDir = Files.createTempDirectory(customBaseDir, customDirPrefix);
 System.out.println("Created temp folder as: " + tmpDir);
 Path tmpFile1 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
 Path tmpFile2 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
 try (DirectoryStreamPath> ds = Files.newDirectoryStream(tmpDir)) 
 // simulate some operations with temp file until delete it
> catch (IOException | InterruptedException e) 

It is advisable to only rely on this method ( deleteOnExit() ) when the application manages a small number of temporary folders/files. This method may consume a lot of memory (it consumes memory for each temporary resource that’s registered for deletion) and this memory may not be released until JVM terminates.

Pay attention, since this method needs to be called in order to register each temporary resource, and the deletion takes place in reverse order of registration (for example, we must register a temporary folder before registering its content).

Deleting a Temporary File via DELETE_ON_CLOSE

Another solution when it comes to deleting a temporary file relies on StandardOpenOption.DELETE_ON_CLOSE (this deletes the file when the stream is closed). For example, the following piece of code creates a temporary file via the createTempFile() method and opens a buffered writer stream for it with DELETE_ON_CLOSE explicitly specified:

Источник

How to Get Temp Directory Path in Java

In this post, we will see how to get temp directory path in java.

Get Temp Directory Path in Java

Using System.getProperty()

To get the temp directory path, you can simply use System.getProperty(«java.io.tmpdir») . It will return default temporary folder based on your operating system.

Default temp directory path
Windows : %USER%\AppData\Local\Temp
Linux/Unix: /tmp

Let’s see with the help of example:

By Creating Temp File and Extracting Temp Path

We can also create temp file and extract temp directory path using String’s substring() method.

Using java.io.File

To get temp directory path:

  • Use File.createTempFile() to create temp file.
  • Get absolute path using File’s getAbsolutePath() method.
  • Use substring() method to extract temp directory path from absolute path.

Using java.nio.File.Files

To get temp directory path:

  • Use Files.createTempFile() to create temp file.
  • Get absolute path using toString() method.
  • Use substring() method to extract temp directory path from absolute path.

Further reading:

How to get current working directory in java
How to get home directory in java

Override Default Temp Directory Path

If you want to override temp directory path, you can run java program with JVM arguments as -Djava.io.tmpdir=Temo_file_path

For example:
If you want set temp directory path as C:\temp , you can run java program with JVM argument as -Djava.io.tmpdir=C:\temp

That’s all about how to get temp directory path in Java.

Was this post helpful?

Count Files in Directory in Java

Count Files in Directory in Java

How to Remove Extension from Filename in Java

How to Remove Extension from Filename in Java

How to Get Temp Directory Path in Java

How to Get Temp Directory Path in Java

Convert OutputStream to byte array in java

Convert Outputstream to Byte Array in Java

How to get current working directory in java

How to get current working directory in java

Difference between Scanner and BufferReader in java

Difference between Scanner and BufferReader in java

Read UTF-8 Encoded Data in java

Read UTF-8 Encoded Data in java

WriteUTF-8NewBufferWriter

Write UTF-8 Encoded Data in java

Java read file line by line

Java read file line by line

Java FileWriter Example

Java FileWriter Example

Java FileReader Example

Java FileReader Example

Java - Create new file

Java – Create new file

Share this

Author

Count Files in Directory in Java

Count Files in Directory in Java

Table of ContentsUsing java.io.File ClassUse File.listFiles() MethodCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count Files & Folders in Current Directory (Excluding Sub-directories)Count Files & Folders in Current Directory (Including Sub-directories)Use File.list() MethodUsing java.nio.file.DirectoryStream ClassCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count […]

How to Remove Extension from Filename in Java

Table of ContentsWays to Remove extension from filename in javaUsing substring() and lastIndexOf() methodsUsing replaceAll() methodUsing Apache common library In this post, we will see how to remove extension from filename in java. Ways to Remove extension from filename in java There are multiple ways to remove extension from filename in java. Let’s go through […]

Convert OutputStream to byte array in java

Convert Outputstream to Byte Array in Java

Table of ContentsConvert OutputStream to Byte array in JavaConvert OutputStream to ByteBuffer in Java In this post, we will see how to convert OutputStream to Byte array in Java. Convert OutputStream to Byte array in Java Here are steps to convert OutputStream to Byte array in java. Create instance of ByteArrayOutputStream baos Write data to […]

How to get current working directory in java

Difference between Scanner and BufferReader in java

Table of ContentsIntroductionScannerBufferedReaderDifference between Scanner and BufferedReader In this post, we will see difference between Scanner and BufferReader in java. Java has two classes that have been used for reading files for a very long time. These two classes are Scanner and BufferedReader. In this post, we are going to find major differences and similarities […]

Read UTF-8 Encoded Data in java

Table of ContentsUsing Files’s newBufferedReader()Using BufferedReaderUsing DataInputStream’s readUTF() method In this post, we will see how to read UTF-8 Encoded Data. Sometimes, we have to deal with UTF-8 Encoded Data in our application. It may be due localization or may be processing data from user input. There are multiple ways to read UTF-8 Encoded Data […]

Источник

Оцените статью