Creating a temporary folder/file

Creating a temporary folder can be accomplished using Path createTempDirectory​(Path dir, String prefix, FileAttribute<?>... attrs). This is a static method in the Files class that can be used as follows:

  • Let's create a temporary folder in the OS's default location with no prefix:
// C:UsersAnghelAppDataLocalTemp8083202661590940905
Path tmpNoPrefix = Files.createTempDirectory(null);
  • Let's create a temporary folder in the OS's default location with a custom prefix:
// C:UsersAnghelAppDataLocalTemplogs_5825861687219258744
String customDirPrefix = "logs_";
Path tmpCustomPrefix
= Files.createTempDirectory(customDirPrefix);
  • Let's create a temporary folder in a custom location with a custom prefix:
// D:	mplogs_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 Path createTempFile​(Path dir, String prefix, String suffix, FileAttribute<?>... attrs). This is a static method in the Files class that can be used as follows:

  • Let's create a temporary file in the OS's default location with no prefix and suffix:
// C:UsersAnghelAppDataLocalTemp16106384687161465188.tmp
Path tmpNoPrefixSuffix = Files.createTempFile(null, null);
  • Let's create a temporary file in the OS's default location with a custom prefix and suffix:
// C:UsersAnghelAppDataLocalTemplog_402507375350226.txt
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomPrefixAndSuffix
= Files.createTempFile(customFilePrefix, customFileSuffix);
  • Let's create a temporary file in a custom location with a custom prefix and suffix:
// D:	mplog_13299365648984256372.txt
Path customBaseDir
= FileSystems.getDefault().getPath("D:/tmp");
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomLocationPrefixSuffix = Files.createTempFile(
customBaseDir, customFilePrefix, customFileSuffix);

In the following sections, we'll take a look at the different ways we can delete a temporary folder/file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.167