Java find temp files

Как получить временный путь к файлу в Java

В Java мы можем использовать System.getProperty (“java.io.tmpdir”), чтобы получить временное местоположение файла.

В Java мы можем использовать System.getProperty(«java.io.tmpdir») , чтобы получить местоположение временного файла по умолчанию.

  1. Для Windows временная папка по умолчанию – % ПОЛЬЗОВАТЕЛЬ%\AppData\Локальный\Временный
  2. Для Linux временной папкой по умолчанию является /tmp

1. Для Linux временной папкой по умолчанию является ||/tmp

Запустите приведенную ниже программу Java на Ubuntu Linux.

package com.mkyong.io.temp; public class TempFilePath1 < public static void main(String[] args) < String tmpdir = System.getProperty("java.io.tmpdir"); System.out.println("Temp file path: " + tmpdir); >>

2. Создать Временный Файл

В качестве альтернативы мы можем создать временный файл и подстроку путь к файлу для получения временного расположения файла.

package com.mkyong.io.temp; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class TempFilePath2 < public static void main(String[] args) < // Java NIO try < Path temp = Files.createTempFile("", ".tmp"); String absolutePath = temp.toString(); System.out.println("Temp file : " + absolutePath); String separator = FileSystems.getDefault().getSeparator(); String tempFilePath = absolutePath .substring(0, absolutePath.lastIndexOf(separator)); System.out.println("Temp file path : " + tempFilePath); >catch (IOException e) < e.printStackTrace(); >> >
Temp file : /tmp/log_11536339146653799756.tmp Temp file path : /tmp

2.2 Пример ввода-вывода Java.

package com.mkyong.io.temp; import java.io.File; import java.io.IOException; public class TempFilePath3 < public static void main(String[] args) < // Java IO try < File temp = File.createTempFile("log_", ".tmp"); System.out.println("Temp file : " + temp.getAbsolutePath()); String absolutePath = temp.getAbsolutePath(); String tempFilePath = absolutePath .substring(0, absolutePath.lastIndexOf(File.separator)); System.out.println("Temp file path : " + tempFilePath); >catch (IOException e) < e.printStackTrace(); >> >
Temp file : /tmp/log_9219838414378386507.tmp Temp file path : /tmp

Скачать Исходный Код

Рекомендации

Источник

Читайте также:  Json loads python примеры

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).

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:

Источник

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