Files create temp file java

Class File

The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.

The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .

  • For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
  • For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Читайте также:  Vectors in java util

Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.

A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Interoperability with java.nio.file package

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.

Источник

How to Create a Temporary File in Java

Last updated: 27 October 2020 There are times when we need to create temporary files on the fly to store some information and delete them afterwards. In Java, we can use Files.createTempFile() methods to create temporary files.

Create Temporary Files

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class CreateTempFile < public static void main(String[] args) < try < // Create a temporary file Path tempFile = Files.createTempFile("temp-", ".txt"); System.out.println("Temp file : " + temp); >catch (IOException e) < e.printStackTrace(); >> > 
Temp file : /var/folders/nyckvw0000gr/T/temp-2129139085984899264.txt 

Note: By default Java creates the temporary file in the temporary directory. We can get the temporary directory by doing System.getProperty(«java.io.tmpdir»)

Path tempFile = Files.createTempFile("prefix-", null); System.out.println("Temp file : " + tempFile); // Temp file : /var/folders/nyckvw0000gr/T/prefix-17184288103181464441.tmp 
Path tempFile = Files.createTempFile(null, ""); System.out.println("Temp file : " + tempFile); // Temp file : /var/folders/nyckvw0000gr/T/1874152090427250275 

Create a Temp File in a Specified Directory

Rather than letting Java choose the directory, we can tell it where to create the temporary file. For example:

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateTempFile < public static void main(String[] args) < try < Path path = Paths.get("target/tmp/"); // Create a temporary file in the specified directory. Path tempFile = Files.createTempFile(path, null, ".log"); System.out.println("Temp file : " + temp); >catch (IOException e) < e.printStackTrace(); >> > 

Create a Temp File and Write to it

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateTempFile < public static void main(String[] args) < try < Path path = Paths.get("target/tmp/"); // Create an temporary file in a specified directory. Path tempFile = Files.createTempFile(path, null, ".log"); System.out.println("Temp file : " + tempFile); // write a line Files.write(tempFile, "Hello From Temp File\n".getBytes(StandardCharsets.UTF_8)); >catch (IOException e) < e.printStackTrace(); >> > 

Источник

Читайте также:  Loading json file in java

Как создать временный файл в Java

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

В этой статье вы научитесь способам создания временных файлов в Java. Есть два статических метода с названием createTempFile в классе Java File, один из них требует два аргумента а другой — три. Это поможет создать временный файл в местоположении по умолчанию временного каталога, а также используется для создания временного файла в указанном месте.

1. Используйте метод File.createTempFile(String prefix, String suffix)

Formal Syntax

public static File createTempFile(String prefix, String suffix) throws IOException

Это легкий способ создания временного файла в временном каталоге операционной системы.

Этот метод создает пустой файл в каталоге по умолчанию для временного файла, используя указанный префикс и суффикс для создания названия этого файла. Использование этого метода эквивалентно к использованию createTempFile(prefix, suffix, null).

Он возвращает абстрактный путь, который указывает на только что созданный пустой файл.

Данный метод имеет следующие параметры:

  • prefix — используется для создания названия файла и может иметь как минимум три символа.
  • suffix -используется для создания названия файла и может быть null, в случае которого будет использован суффикс «.tmp». /li>

Пример

import java.io.File; import java.io.IOException; public class JavaTempFile < public static void main(String[] args) < try < File tmpFile = File.createTempFile("data", null); File newFile = File.createTempFile("text", ".temp", new File("/Users/name/temp")); System.out.println(tmpFile.getCanonicalPath()); System.out.println(newFile.getCanonicalPath()); // запишите данные в временный файл подобно обычному файлу // удалите при завершении программы tmpFile.deleteOnExit(); newFile.deleteOnExit(); > catch (IOException e) < e.printStackTrace(); > > >

Результат

/private/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/data225458400489752329.tmp /Users/name/temp/text2548249124983543974.temp

Временный файл не будет удален после того, как Java программа завершила работу, если вы не создали второй временный Java файл, вызывающий метод deleteOnExit класса Java File. Этот аргумент влияет на то, как будет работать ваш временный файл Java.

Читайте также:  Php посмотреть глобальные переменные

2. Используйте метод File.createTempFile(String prefix, String suffix, File directory)

Формальный синтаксис

public static File createTempFile(String prefix, String suffix, File directory) throws IOException
  • Префикс (prefix) — The prefix string to be used in generating the file’s name; must be at least three characters long.
  • Суффикс (suffix) — The suffix string to be used in generating the file’s name; may be null, in which case the suffix «.tmp» will be used.
  • Каталог (directory) — The directory in which the file is to be created, or null if the default temporary-file directory is to be used.

Этот метод возвращает абстрактный путь, который указывает на недавно созданный пустой файл. Он вызывает IOException, если файл не может быть создан,IllegalArgumentException, если аргумент префикса содержит меньше трех символов и SecurityException, если есть диспетчер безопасности, и его метод java.lang.SecurityManager.checkWrite(java.lang.String) не позволяет создать файл.1

А теперь увидим этот метод в работе:

Пример

import java.io.File; import java.io.IOException; public class TempFileExample < public static void main(String[] args) < try < File tempFile = File.createTempFile("hello", ".tmp"); System.out.println("Temp file On Default Location: " + tempFile.getAbsolutePath()); tempFile = File.createTempFile("hello", ".tmp", new File("C:/")); System.out.println("Temp file On Specified Location: " + tempFile.getAbsolutePath()); > catch (IOException e) < e.printStackTrace(); >>

Результат будет иметь следующий вид:

Temp file On Default Location: C:\Users\swami\AppData\Local\Temp\hello7828748332363277400.tmp Temp file On Specified Location: C:\hello950036450024130433.tmp

В случае тестов модулей, используемых JUnit, можете также использовать TemporaryFolder. TemporaryFolder Rule позволяет создать файлы и папки, которые должны быть удалены при завершении тестового метода независимо от его результата.

В заключении здесь увидите некоторые заметки относительно временных файлов класса Java File:

  • Перейдите к методу deleteOnExit() с помощью метода createTempFile() с версией трех аргументов, чтобы автоматически избавиться от временных файлов.
  • Если говорить о deleteOnExit(), Javadoc предоставляет информацию, что удаление будет предпринято при нормальном завершении виртуальной машины, как указано в спецификации языка Java

Источник

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