Java : Files with Examples

Files (Java SE 22 & JDK 22) with Examples.
You will find code examples on most Files methods.


Summary

This class consists exclusively of static methods that operate on files, directories, or other types of files.

Class diagram

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

Files.writeString(path, "abcd");

System.out.println(Files.exists(path)); // true
System.out.println(Files.readString(path)); // abcd

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2024/10/19    15:48              4 aaa.txt

Files.delete(path);
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

Annotation :

  • Most of the code examples in this article are run on Windows.
  • Some of the code examples are run on Linux for POSIX.

Methods

static long copy (InputStream in, Path target, CopyOption... options)

Copies all bytes from an input stream to a file.

final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.writeString(source, "abcd");
System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt

try (final var in = Files.newInputStream(source)) {
    final var ret = Files.copy(in, target);
    System.out.println(ret); // 4
}

final var str = Files.readString(target);
System.out.println(str); // abcd

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt
final var url = URI.create("https://example.com").toURL();
System.out.println(url); // https://example.com

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt
System.out.println(Files.notExists(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

try (final var in = url.openStream()) {
    final var ret = Files.copy(in, target);
    System.out.println(ret); // 1256
}

final var str = Files.readString(target);
System.out.println(str);

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
//...
final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.createFile(target);
System.out.println(Files.exists(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//target.txt

final byte[] buf = {10, 20, 30};

try (final var in = new ByteArrayInputStream(buf)) {
    Files.copy(in, target);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!

try (final var in = new ByteArrayInputStream(buf)) {
    Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
    System.out.println(Arrays.toString(Files.readAllBytes(target)));
}

// Result
// ↓
//[10, 20, 30]

static long copy (Path source, OutputStream out)

Copies all bytes from a file to an output stream.

final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.writeString(source, "abcd");
System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt

try (final var out = Files.newOutputStream(target)) {
    final var ret = Files.copy(source, out);
    System.out.println(ret); // 4
}

final var str = Files.readString(target);
System.out.println(str); // abcd

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt
final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

Files.write(source, new byte[]{10, 20, 30});
System.out.println(Files.exists(source)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt

try (final var out = new ByteArrayOutputStream()) {
    final var ret = Files.copy(source, out);
    System.out.println(ret); // 3

    System.out.println(Arrays.toString(out.toByteArray())); // [10, 20, 30]
}
final var source = Path.of("D:", "java-work", "xxx");
System.out.println(source); // D:\java-work\xxx
System.out.println(Files.notExists(source)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

try (final var out = new ByteArrayOutputStream()) {
    Files.copy(source, out);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Path copy (Path source, Path target, CopyOption... options)

Copy a file to a target file.

final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.writeString(source, "abcd");
System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt

final var ret = Files.copy(source, target);
System.out.println(ret); // D:\java-work\target.txt

final var str = Files.readString(target);
System.out.println(str); // abcd

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt
final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.writeString(source, "abcd");
Files.writeString(target, "XYZ");

System.out.println(Files.readString(source)); // abcd
System.out.println(Files.readString(target)); // XYZ

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt

try {
    Files.copy(source, target);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!

final var ret = Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println(ret); // D:\java-work\target.txt

System.out.println(Files.readString(source)); // abcd
System.out.println(Files.readString(target)); // abcd

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt
final var source = Path.of("D:", "java-work", "xxx");
System.out.println(source); // D:\java-work\xxx

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

System.out.println(Files.notExists(source)); // true
System.out.println(Files.notExists(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

try {
    Files.copy(source, target);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Path createDirectories (Path dir, FileAttribute<?>... attrs)

Creates a directory by creating all nonexistent parent directories first.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.

final var dir = Path.of("D:", "java-work", "dir1");
System.out.println(dir); // D:\java-work\dir1
System.out.println(Files.notExists(dir)); // true

final var ret = Files.createDirectories(dir);
System.out.println(ret); // D:\java-work\dir1

System.out.println(Files.isDirectory(dir)); // true

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.
//└─dir1
// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.

final var dir = Path.of("D:", "java-work", "dir1", "dir2", "dir3");
System.out.println(dir); // D:\java-work\dir1\dir2\dir3
System.out.println(Files.notExists(dir.getParent().getParent())); // true

final var ret = Files.createDirectories(dir);
System.out.println(ret); // D:\java-work\dir1\dir2\dir3

System.out.println(Files.isDirectory(dir)); // true

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.
//└─dir1
//    └─dir2
//        └─dir3
// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

System.out.println(Files.notExists(dir)); // true
System.out.println(Files.createDirectories(dir)); // D:\java-work\dir

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.createDirectories(dir)); // D:\java-work\dir

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.
//└─dir
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);
System.out.println(Files.isDirectory(path)); // false
System.out.println(Files.isRegularFile(path)); // true

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.
//    aaa.txt

try {
    Files.createDirectories(path);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!

static Path createDirectory (Path dir, FileAttribute<?>... attrs)

Creates a new directory.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir
System.out.println(Files.notExists(dir)); // true

final var ret = Files.createDirectory(dir);
System.out.println(ret); // // D:\java-work\dir
System.out.println(Files.isDirectory(dir)); // true

// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.
//└─dir

try {
    Files.createDirectory(dir);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!
// --- PowerShell ---
//PS D:\java-work> tree /F
//
//D:.

final var dir = Path.of("D:", "java-work", "dir1", "dir2", "dir3");
System.out.println(dir); // D:\java-work\dir1\dir2\dir3
System.out.println(Files.notExists(dir.getParent())); // true

try {
    Files.createDirectory(dir);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Path createFile (Path path, FileAttribute<?>... attrs)

Creates a new and empty file, failing if the file already exists.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var ret = Files.createFile(path);
System.out.println(ret); // D:\java-work\aaa.txt
System.out.println(Files.size(path)); // 0

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

try {
    Files.createFile(path);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!
final var path = Path.of("D:", "java-work", "dir", "aaa.txt");
System.out.println(path); // D:\java-work\dir\aaa.txt
System.out.println(Files.notExists(path)); // true

final var parent = path.getParent();
System.out.println(parent); // D:\java-work\dir
System.out.println(Files.notExists(parent)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

try {
    Files.createFile(path);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

The following code runs on Linux.

System.out.println(System.getProperty("os.name")); // Linux

final var ret1 = Files.createFile(Path.of("sample1.txt"));
System.out.println(ret1); // sample1.txt

// --- Linux Terminal ---
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var permissions = PosixFilePermissions.fromString("rw-r-----");
System.out.println(permissions); // [OWNER_READ, OWNER_WRITE, GROUP_READ]

final var ret2 = Files.createFile(
        Path.of("sample2.txt"),
        PosixFilePermissions.asFileAttribute(permissions));
System.out.println(ret2); // sample2.txt

// --- Linux Terminal ---
//$ ls -l sample2.txt
//-rw-r----- 1 xxxx xxxx 0 ... sample2.txt

static Path createLink (Path link, Path existing)

Creates a new link (directory entry) for an existing file (optional operation).

final var existing = Path.of("D:", "java-work", "existing.txt");
System.out.println(existing); // D:\java-work\existing.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.writeString(existing, "abcd");
System.out.println(Files.exists(existing)); // true
System.out.println(Files.exists(link)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Name
//existing.txt

final var ret = Files.createLink(link, existing);
System.out.println(ret); // D:\java-work\link.txt

System.out.println(Files.readString(existing)); // abcd
System.out.println(Files.readString(link)); // abcd

// --- PowerShell ---
//PS D:\java-work> ls -Name
//existing.txt
//link.txt
//
//PS D:\java-work> ls .\link.txt | Format-List
//...
//Mode           : la---
//LinkType       : HardLink
//Target         :
//VersionInfo    : File:             D:\java-work\link.txt
//...

Files.writeString(existing, "XYZ");

System.out.println(Files.readString(existing)); // XYZ
System.out.println(Files.readString(link)); // XYZ
// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var existing = Path.of("D:", "java-work", "existing.txt");
System.out.println(existing); // D:\java-work\existing.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

System.out.println(Files.notExists(existing)); // true
System.out.println(Files.notExists(link)); // true

try {
    Files.createLink(link, existing); // NoSuchFileException
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!
final var existing = Path.of("D:", "java-work", "existing.txt");
System.out.println(existing); // D:\java-work\existing.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(existing);
Files.createFile(link);
System.out.println(Files.exists(existing)); // true
System.out.println(Files.exists(link)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//existing.txt
//link.txt

try {
    Files.createLink(link, existing);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!

static Path createSymbolicLink (Path link, Path target, FileAttribute<?>... attrs)

Creates a symbolic link to a target (optional operation).

Creating a symbolic link may require administrator privileges.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.writeString(target, "abcd");
System.out.println(Files.exists(target)); // true
System.out.println(Files.exists(link)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Name
//target.txt

final var ret = Files.createSymbolicLink(link, target);
System.out.println(ret); // D:\java-work\link.txt

System.out.println(Files.readString(target)); // abcd
System.out.println(Files.readString(link)); // abcd

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt
//-a---  ...        4 target.txt
//
//PS D:\java-work> ls .\link.txt | Format-List
//...
//Mode           : la---
//LinkType       : SymbolicLink
//Target         : D:\java-work\target.txt
//VersionInfo    : File:             D:\java-work\link.txt
//...

Files.writeString(target, "XYZ");

System.out.println(Files.readString(target)); // XYZ
System.out.println(Files.readString(link)); // XYZ
final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

System.out.println(Files.notExists(target)); // true
System.out.println(Files.notExists(link)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

// You can also create empty links.
final var ret = Files.createSymbolicLink(link, target);
System.out.println(ret); // D:\java-work\link.txt

System.out.println(Files.notExists(target)); // true
System.out.println(Files.notExists(link)); // true
System.out.println(Files.isSymbolicLink(link)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt
final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(target);
Files.createFile(link);
System.out.println(Files.exists(target)); // true
System.out.println(Files.exists(link)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//link.txt
//target.txt

try {
    Files.createSymbolicLink(link, target);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!

static Path createTempDirectory (String prefix, FileAttribute<?>... attrs)

Creates a new directory in the default temporary-file directory, using the given prefix to generate its name.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

final var ret1 = Files.createTempDirectory("prefix");
System.out.println(ret1); // C:\Users\xxx\AppData\Local\Temp\prefix6089636834939322082

final var ret2 = Files.createTempDirectory("abcd-");
System.out.println(ret2); // C:\Users\xxx\AppData\Local\Temp\abcd-6998169258402534775

final var ret3 = Files.createTempDirectory(null);
System.out.println(ret3); // C:\Users\xxx\AppData\Local\Temp\7916867536894745055

static Path createTempDirectory (Path dir, String prefix, FileAttribute<?>... attrs)

Creates a new directory in the specified directory, using the given prefix to generate its name.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

final var ret1 = Files.createTempDirectory(dir, "prefix");
System.out.println(ret1); // D:\java-work\prefix18208067467997933175

final var ret2 = Files.createTempDirectory(dir, "abcd-");
System.out.println(ret2); // D:\java-work\abcd-521471602431667304

final var ret3 = Files.createTempDirectory(dir, null);
System.out.println(ret3); // D:\java-work\2640746303774778924

static Path createTempFile (String prefix, String suffix, FileAttribute<?>... attrs)

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

final var ret1 = Files.createTempFile("prefix-", "-suffix");
System.out.println(ret1); // C:\Users\xxx\AppData\Local\Temp\prefix-9091722447586283597-suffix

final var ret2 = Files.createTempFile("abcd-", ".txt");
System.out.println(ret2); // C:\Users\xxx\AppData\Local\Temp\abcd-13867786695402679957.txt

final var ret3 = Files.createTempFile("prefix-", null);
System.out.println(ret3); // C:\Users\xxx\AppData\Local\Temp\prefix-17221573028074243598.tmp

final var ret4 = Files.createTempFile(null, "-suffix");
System.out.println(ret4); // C:\Users\xxx\AppData\Local\Temp\11809310207624726987-suffix

final var ret5 = Files.createTempFile(null, null);
System.out.println(ret5); // C:\Users\xxx\AppData\Local\Temp\13779039011143750638.tmp

static Path createTempFile (Path dir, String prefix, String suffix, FileAttribute<?>... attrs)

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

Please see also createFile(Path path, FileAttribute<?>... attrs) for FileAttribute.

final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

final var ret1 = Files.createTempFile(dir, "prefix-", "-suffix");
System.out.println(ret1); // D:\java-work\prefix-10113412430119575991-suffix

final var ret2 = Files.createTempFile(dir, "abcd-", ".txt");
System.out.println(ret2); // D:\java-work\abcd-169546499978120138.txt

final var ret3 = Files.createTempFile(dir, "prefix-", null);
System.out.println(ret3); // D:\java-work\prefix-9437871265568200345.tmp

final var ret4 = Files.createTempFile(dir, null, "-suffix");
System.out.println(ret4); // D:\java-work\9337658086830323119-suffix

final var ret5 = Files.createTempFile(dir, null, null);
System.out.println(ret5); // D:\java-work\13108613127478405635.tmp

static void delete (Path path)

Deletes a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

Files.createFile(path);
Files.createDirectory(dir);

System.out.println(Files.isRegularFile(path)); // true
System.out.println(Files.isDirectory(dir)); // true

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

Files.delete(path);
System.out.println(Files.notExists(path)); // true

//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir

Files.delete(dir);
System.out.println(Files.notExists(dir)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>
// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(Files.notExists(path)); // true

try {
    Files.delete(path);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─dir
//        aaa.txt
//        bbb.txt

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir
System.out.println(Files.isDirectory(dir)); // true

try {
    Files.delete(dir);
} catch (DirectoryNotEmptyException e) {
    System.out.println("DirectoryNotEmptyException!");
}

// Result
// ↓
//DirectoryNotEmptyException!

static boolean deleteIfExists (Path path)

Deletes a file if it exists.

Please see also : delete(Path path)

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);
System.out.println(Files.exists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

System.out.println(Files.deleteIfExists(path)); // true
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//<No files / directories>

System.out.println(Files.deleteIfExists(path)); // false

static boolean exists (Path path, LinkOption... options)

Tests whether a file exists.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.exists(dir)); // true

System.out.println(Files.isRegularFile(file)); // true
System.out.println(Files.exists(file)); // true

System.out.println(Files.exists(nonExistentPath)); // false
final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

// Intentionally creates an empty link.
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt

System.out.println(Files.exists(target)); // false

System.out.println(Files.isSymbolicLink(link)); // true
System.out.println(Files.exists(link)); // false
System.out.println(Files.exists(link, LinkOption.NOFOLLOW_LINKS)); // true

static Stream<Path> find (Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options)

Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

System.out.println("maxDepth : 3");
try (final var stream = Files.find(start, 3, (_, _) -> true)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 3
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2
//D:\java-work\dir1\dir1-2\eee.txt
//D:\java-work\dir1\dir1-2\fff.txt
//D:\java-work\dir2
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt

System.out.println("maxDepth : 2");
try (final var stream = Files.find(start, 2, (_, _) -> true)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 2
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2
//D:\java-work\dir2
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt

System.out.println("maxDepth : 1");
try (final var stream = Files.find(start, 1, (_, _) -> true)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 1
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir2

System.out.println("maxDepth : 0");
try (final var stream = Files.find(start, 0, (_, _) -> true)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 0
//D:\java-work
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

System.out.println("matcher : isDirectory");
try (final var stream = Files.find(start, Integer.MAX_VALUE,
        (_, basicFileAttributes) -> basicFileAttributes.isDirectory())) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//matcher : isDirectory
//D:\java-work
//D:\java-work\dir1
//D:\java-work\dir1\dir1-2
//D:\java-work\dir2

System.out.println("matcher : isRegularFile");
try (final var stream = Files.find(start, Integer.MAX_VALUE,
        (_, basicFileAttributes) -> basicFileAttributes.isRegularFile())) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//matcher : isRegularFile
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2\eee.txt
//D:\java-work\dir1\dir1-2\fff.txt
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//├─dir
//│      aaa.txt
//│      bbb.txt
//│
//└─link-dir
//        aaa.txt
//        bbb.txt
//
//PS D:\java-work> ls
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//l----  ...          link-dir -> D:\java-work\dir

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

try (final var stream = Files.find(start, Integer.MAX_VALUE,
        (_, _) -> true)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//D:\java-work\link-dir

System.out.println("FileVisitOption : FOLLOW_LINKS");
try (final var stream = Files.find(start, Integer.MAX_VALUE,
        (_, _) -> true, FileVisitOption.FOLLOW_LINKS)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//FileVisitOption : FOLLOW_LINKS
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//D:\java-work\link-dir
//D:\java-work\link-dir\aaa.txt
//D:\java-work\link-dir\bbb.txt
final var start = Path.of("D:", "java-work", "xxx");
System.out.println(start); // D:\java-work\xxx
System.out.println(Files.notExists(start)); // true

try (var _ = Files.find(start, Integer.MAX_VALUE, (_, _) -> true)) {
    System.out.println("No errors");
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Object getAttribute (Path path, String attribute, LinkOption... options)

Reads the value of a file attribute.

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var hidden = Path.of("D:", "java-work", "hidden.txt");
System.out.println(hidden); // D:\java-work\hidden.txt

Files.writeString(file, "abcd");

Files.writeString(hidden, "1234567890");
Files.setAttribute(hidden, "dos:hidden", true);

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a---      4 aaa.txt
//-a-h-     10 hidden.txt

System.out.println(Files.getAttribute(file, "size")); // 4
System.out.println(Files.getAttribute(hidden, "size")); // 10

System.out.println(Files.getAttribute(file, "dos:hidden")); // false
System.out.println(Files.getAttribute(hidden, "dos:hidden")); // true
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.writeString(target, "abcd");
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        4 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

System.out.println(Files.getAttribute(link, "size")); // 4
System.out.println(Files.getAttribute(link, "size", LinkOption.NOFOLLOW_LINKS)); // 0

static <V extends FileAttributeView> V getFileAttributeView (Path path, Class<V> type, LinkOption... options)

Returns a file attribute view of a given type.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, "abcd");

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a---      4 aaa.txt

final var basicView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
if (basicView != null) {
    final var attrs = basicView.readAttributes();
    System.out.println(attrs.size()); // 4
    System.out.println(attrs.isRegularFile()); // true
    System.out.println(attrs.isDirectory()); // false
}
final var hidden = Path.of("D:", "java-work", "hidden.txt");
System.out.println(hidden); // D:\java-work\hidden.txt

Files.writeString(hidden, "abcd");
Files.setAttribute(hidden, "dos:hidden", true);

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a-h-      4 hidden.txt

final var dosView = Files.getFileAttributeView(hidden, DosFileAttributeView.class);
if (dosView != null) {
    final var attrs = dosView.readAttributes();
    System.out.println(attrs.size()); // 4
    System.out.println(attrs.isHidden()); // true
    System.out.println(attrs.isReadOnly()); // false

    dosView.setReadOnly(true);

    // --- PowerShell ---
    //PS D:\java-work> ls -Force | Format-Table -Property Mode, Length, Name
    //
    //Mode  Length Name
    //----  ------ ----
    //-arh-      4 hidden.txt
}
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.writeString(target, "abcd");
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        4 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

final var basicView = Files.getFileAttributeView(
        link, BasicFileAttributeView.class);
if (basicView != null) {
    final var attrs = basicView.readAttributes();
    System.out.println(attrs.size()); // 4
    System.out.println(attrs.isRegularFile()); // true
    System.out.println(attrs.isSymbolicLink()); // false
}

final var basicView2 = Files.getFileAttributeView(
        link, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
if (basicView2 != null) {
    final var attrs = basicView2.readAttributes();
    System.out.println(attrs.size()); // 0
    System.out.println(attrs.isRegularFile()); // false
    System.out.println(attrs.isSymbolicLink()); // true
}

static FileStore getFileStore (Path path)

Returns the FileStore representing the file store where a file is located.

final var path = Path.of("D:", "java-work");
System.out.println(path); // D:\java-work

final var store = Files.getFileStore(path);

System.out.println(store.type()); // NTFS
System.out.println(store.getBlockSize()); // 512

static FileTime getLastModifiedTime (Path path, LinkOption... options)

Returns a file's last modified time.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var ret = Files.setLastModifiedTime(path, FileTime.from(
        ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId).toInstant()));
System.out.println(ret); // D:\java-work\aaa.txt

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property LastWriteTime, Name
//
//LastWriteTime      Name
//-------------      ----
//2100/01/01 0:00:00 aaa.txt

// FileTime is UTC.
final var fileTime = Files.getLastModifiedTime(path);
System.out.println(fileTime); // 2099-12-31T15:00:00Z

final var zonedDateTime = ZonedDateTime.ofInstant(fileTime.toInstant(), zoneId);
System.out.println(zonedDateTime); // 2100-01-01T00:00+09:00[Asia/Tokyo]
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var zonedDateTime = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId);
System.out.println(zonedDateTime); // 2100-01-01T00:00+09:00[Asia/Tokyo]

Files.createFile(target);
Files.setLastModifiedTime(target, FileTime.from(zonedDateTime.toInstant()));

Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2100/01/01     0:00              0 aaa.txt
//la---          2024/10/19    16:31              0 link.txt -> D:\java-work\aaa.txt

final var ret1 = Files.getLastModifiedTime(link);
System.out.println(ret1); // 2099-12-31T15:00:00Z

final var ret2 = Files.getLastModifiedTime(link, LinkOption.NOFOLLOW_LINKS);
System.out.println(ret2); // 2024-10-19T07:31:55.9393338Z

static UserPrincipal getOwner (Path path, LinkOption... options)

Returns the owner of a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);

final var service = path.getFileSystem().getUserPrincipalLookupService();
final var newOwner = service.lookupPrincipalByName("test-user");

final var ret1 = Files.setOwner(path, newOwner);
System.out.println(ret1); // D:\java-work\aaa.txt

// --- PowerShell ---
//PS D:\java-work> Get-Acl .\aaa.txt
//...
//Path    Owner           Access
//----    -----           ------
//aaa.txt MY-PC\test-user BUILTIN\Administrators Allow  FullControl…

final var ret2 = Files.getOwner(path);
System.out.println(ret2); // MY-PC\test-user (User)
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls | Get-Acl
//..
//Path     Owner                    Access
//----     -----                    ------
//aaa.txt  MY-PC\test-user          BUILTIN\Administrators Allow  FullControl…
//link.txt BUILTIN\Administrators   BUILTIN\Administrators Allow  FullControl…

final var ret1 = Files.getOwner(link);
System.out.println(ret1); // MY-PC\test-user (User)

final var ret2 = Files.getOwner(link, LinkOption.NOFOLLOW_LINKS);
System.out.println(ret2); // BUILTIN\Administrators (Alias)

static Set<PosixFilePermission> getPosixFilePermissions (Path path, LinkOption... options)

Returns a file's POSIX file permissions.

The following code runs on Linux.

System.out.println(System.getProperty("os.name")); // Linux

// --- Linux Terminal ---
//$ ls -l sample.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample.txt

final var path = Path.of("sample.txt");

final var permissions = Files.getPosixFilePermissions(path);
System.out.println(PosixFilePermissions.toString(permissions)); // rw-rw-r--
System.out.println(System.getProperty("os.name")); // Linux

// --- Linux Terminal ---
//$ ls -l
//lrwxrwxrwx 1 xxxx xxxx 10 ... link.txt -> sample.txt
//-rw-rw-r-- 1 xxxx xxxx  0 ... sample.txt

final var path = Path.of("link.txt");

final var permissions1 = Files.getPosixFilePermissions(path);
System.out.println(PosixFilePermissions.toString(permissions1)); // rw-rw-r--

final var permissions2 = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS);
System.out.println(PosixFilePermissions.toString(permissions2)); // rwxrwxrwx

static boolean isDirectory (Path path, LinkOption... options)

Tests whether a file is a directory.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link-dir");
System.out.println(link); // D:\java-work\link-dir

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);
Files.createSymbolicLink(link, dir);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//l----  ...          link-dir -> D:\java-work\dir
//-a---  ...        0 aaa.txt

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.isDirectory(file)); // false

System.out.println(Files.isDirectory(link)); // true
System.out.println(Files.isDirectory(link, LinkOption.NOFOLLOW_LINKS)); // false

System.out.println(Files.isDirectory(nonExistentPath)); // false

static boolean isExecutable (Path path)

Tests whether a file is executable.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var exe = Path.of("D:", "java-work", "java.exe");
System.out.println(exe); // D:\java-work\java.exe

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);
Files.copy(Path.of(System.getProperty("java.home"), "bin", "java.exe"), exe);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt
//-a--- java.exe

// On Windows.
System.out.println(Files.isExecutable(dir)); // true
System.out.println(Files.isExecutable(file)); // true
System.out.println(Files.isExecutable(exe)); // true
System.out.println(Files.isExecutable(nonExistentPath)); // false

The following code runs on Linux.

System.out.println(System.getProperty("os.name")); // Linux

final var shFile = Path.of("sample.sh");
final var txtFile = Path.of("sample.txt");

// --- Linux Terminal ---
//$ ls -l
//-rwxrwxr-x 1 xxxx xxxx    0 ... sample.sh
//-rw-rw-r-- 1 xxxx xxxx    0 ... sample.txt

System.out.println(Files.isExecutable(shFile)); // true
System.out.println(Files.isExecutable(txtFile)); // false

static boolean isHidden (Path path)

Tells whether or not a file is considered hidden.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var hidden = Path.of("D:", "java-work", "hidden.txt");
System.out.println(hidden); // D:\java-work\hidden.txt

Files.createDirectory(dir);
Files.createFile(file);

Files.createFile(hidden);
Files.setAttribute(hidden, "dos:hidden", true);

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt
//-a-h- hidden.txt

System.out.println(Files.isHidden(dir)); // false
System.out.println(Files.isHidden(file)); // false
System.out.println(Files.isHidden(hidden)); // true
final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx
System.out.println(Files.notExists(nonExistentPath)); // true

try {
    Files.isHidden(nonExistentPath);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static boolean isReadable (Path path)

Tests whether a file is readable.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(Files.isReadable(dir)); // true
System.out.println(Files.isReadable(file)); // true
System.out.println(Files.isReadable(nonExistentPath)); // false
// The non-readable.txt has read permission denied.
final var nonReadableFile = Path.of("D:", "java-work", "non-readable.txt");
System.out.println(nonReadableFile); // D:\java-work\non-readable.txt

// --- PowerShell ---
//PS D:\java-work> Get-Acl .\non-readable.txt
//...
//Path             Owner           Access
//----             -----           ------
//non-readable.txt MY-PC\test-user BUILTIN\Administrators Deny  ReadData…

System.out.println(Files.isReadable(nonReadableFile)); // false

static boolean isRegularFile (Path path, LinkOption... options)

Tests whether a file is a regular file with opaque content.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);
Files.createSymbolicLink(link, file);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//-a---  ...        0 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.isRegularFile(dir)); // false

System.out.println(Files.exists(file)); // true
System.out.println(Files.isRegularFile(file)); // true

System.out.println(Files.isSymbolicLink(link)); // true
System.out.println(Files.isRegularFile(link)); // true
System.out.println(Files.isRegularFile(link, LinkOption.NOFOLLOW_LINKS)); // false

System.out.println(Files.notExists(nonExistentPath)); // true
System.out.println(Files.isRegularFile(nonExistentPath)); // false

static boolean isSameFile (Path path, Path path2)

Tests if two paths locate the same file.

final var file1 = Path.of("D:", "java-work", "aaa1.txt");
System.out.println(file1); // D:\java-work\aaa1.txt

final var file2 = Path.of("D:", "java-work", "aaa2.txt");
System.out.println(file2); // D:\java-work\aaa2.txt

final var file3 = Path.of("D:", "java-work", "bbb.txt");
System.out.println(file3); // D:\java-work\bbb.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.writeString(file1, "abcd");
Files.writeString(file2, "abcd");
Files.writeString(file3, "XYZ");
Files.createSymbolicLink(link, file1);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        4 aaa1.txt
//-a---  ...        4 aaa2.txt
//-a---  ...        3 bbb.txt
//la---  ...        0 link.txt -> D:\java-work\aaa1.txt

System.out.println(Files.readString(file1)); // abcd
System.out.println(Files.readString(file2)); // abcd
System.out.println(Files.readString(file3)); // XYZ
System.out.println(Files.readString(link)); // abcd

System.out.println(Files.isSameFile(file1, file1)); // true
System.out.println(Files.isSameFile(file1, file2)); // false
System.out.println(Files.isSameFile(file1, file3)); // false
System.out.println(Files.isSameFile(file1, link)); // true
final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createFile(file);

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

try {
    Files.isSameFile(file, nonExistentPath);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static boolean isSymbolicLink (Path path)

Tests whether a file is a symbolic link.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);
Files.createSymbolicLink(link, file);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//-a---  ...        0 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.isSymbolicLink(dir)); // false

System.out.println(Files.isRegularFile(file)); // true
System.out.println(Files.isSymbolicLink(file)); // false

System.out.println(Files.exists(link)); // true
System.out.println(Files.isSymbolicLink(link)); // true

System.out.println(Files.notExists(nonExistentPath)); // true
System.out.println(Files.isSymbolicLink(nonExistentPath)); // false

static boolean isWritable (Path path)

Tests whether a file is writable.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var readOnlyFile = Path.of("D:", "java-work", "read-only.txt");
System.out.println(readOnlyFile); // D:\java-work\read-only.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);

Files.createFile(readOnlyFile);
Files.setAttribute(readOnlyFile, "dos:readonly", true);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt
//-ar-- read-only.txt

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.isWritable(dir)); // true

System.out.println(Files.isRegularFile(file)); // true
System.out.println(Files.isWritable(file)); // true

System.out.println(Files.isRegularFile(readOnlyFile)); // true
System.out.println(Files.isWritable(readOnlyFile)); // false

System.out.println(Files.notExists(nonExistentPath)); // true
System.out.println(Files.isWritable(nonExistentPath)); // false

static Stream<String> lines (Path path)

Read all lines from a file as a Stream.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, """
        abcd
        XYZ
        12345
        """);

try (final var lines = Files.lines(path)) {
    System.out.println(lines.toList()); // [abcd, XYZ, 12345]
}
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);
System.out.println(Files.size(path)); // 0

try (final var stream = Files.lines(path)) {
    System.out.println(stream.toList()); // []
}

static Stream<String> lines (Path path, Charset cs)

Read all lines from a file as a Stream.

Please see also : lines(Path path)

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path);

final var csq = """
        abcd
        12345
        〇△□×
        """;

Files.writeString(path, csq, StandardCharsets.UTF_8);

try (final var stream = Files.lines(path, StandardCharsets.UTF_8)) {
    System.out.println(stream.toList()); // [abcd, 12345, 〇△□×]
}

try (final var stream = Files.lines(path, Charset.forName("Shift_JIS"))) {
    var _ = stream.toList();
} catch (UncheckedIOException e) {
    System.out.println("UncheckedIOException! : " + e.getMessage());
}

// Result
// ↓
//UncheckedIOException! : java.nio.charset.MalformedInputException: Input length = 1
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path);

final var csq = """
        abcd
        12345
        〇△□×
        """;

Files.writeString(path, csq, Charset.forName("Shift_JIS"));

try (final var stream = Files.lines(path, Charset.forName("Shift_JIS"))) {
    System.out.println(stream.toList()); // [abcd, 12345, 〇△□×]
}

try (final var stream = Files.lines(path, StandardCharsets.UTF_8)) {
    var _ = stream.toList();
} catch (UncheckedIOException e) {
    System.out.println("UncheckedIOException! : " + e.getMessage());
}

// Result
// ↓
//UncheckedIOException! : java.nio.charset.MalformedInputException: Input length = 1

static Stream<Path> list (Path dir)

Return a lazily populated Stream, the elements of which are the entries in the directory.

final var dir1 = Path.of("D:", "java-work");
System.out.println(dir1); // D:\java-work

Files.createFile(dir1.resolve(Path.of("aaa.txt")));
Files.createFile(dir1.resolve(Path.of("bbb.txt")));

final var dir2 = dir1.resolve("dir");
System.out.println(dir2); // D:\java-work\dir

Files.createDirectory(dir2);
Files.createFile(dir2.resolve(Path.of("ccc.txt")));
Files.createFile(dir2.resolve(Path.of("ddd.txt")));

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//└─dir
//        ccc.txt
//        ddd.txt

try (final var stream = Files.list(dir1)) {
    stream.forEach(System.out::println);

    // Result
    // ↓
    //D:\java-work\aaa.txt
    //D:\java-work\bbb.txt
    //D:\java-work\dir
}

try (final var stream = Files.list(dir2)) {
    stream.forEach(System.out::println);

    // Result
    // ↓
    //D:\java-work\dir\ccc.txt
    //D:\java-work\dir\ddd.txt
}
final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

Files.createFile(file);
System.out.println(Files.isRegularFile(file)); // true

try (var _ = Files.list(file)) {
    System.out.println("No errors");
} catch (NotDirectoryException e) {
    System.out.println("NotDirectoryException!");
}

// Result
// ↓
//NotDirectoryException!

static long mismatch (Path path, Path path2)

Finds and returns the position of the first mismatched byte in the content of two files, or -1L if there is no mismatch.

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var file1 = Path.of("D:", "java-work", "aaa1.txt");
final var file2 = Path.of("D:", "java-work", "aaa2.txt");
final var file3 = Path.of("D:", "java-work", "aaa3.txt");
final var file4 = Path.of("D:", "java-work", "aaa4.txt");
final var file5 = Path.of("D:", "java-work", "aaa5.txt");
final var file6 = Path.of("D:", "java-work", "aaa6.txt");

Files.write(target, new byte[]{0, 1, 2});

Files.write(file1, new byte[]{0, 1, 2});
Files.write(file2, new byte[]{0, 1, 102});
Files.write(file3, new byte[]{0, 101, 102});
Files.write(file4, new byte[]{100, 101, 102});
Files.write(file5, new byte[]{});
Files.write(file6, new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa1.txt
//aaa2.txt
//aaa3.txt
//aaa4.txt
//aaa5.txt
//aaa6.txt
//target.txt

System.out.println(Arrays.toString(Files.readAllBytes(target))); // [0, 1, 2]

System.out.println(Arrays.toString(Files.readAllBytes(file1))); // [0, 1, 2]
System.out.println(Files.mismatch(target, file1)); // -1

System.out.println(Arrays.toString(Files.readAllBytes(file2))); // [0, 1, 102]
System.out.println(Files.mismatch(target, file2)); // 2

System.out.println(Arrays.toString(Files.readAllBytes(file3))); // [0, 101, 102]
System.out.println(Files.mismatch(target, file3)); // 1

System.out.println(Arrays.toString(Files.readAllBytes(file4))); // [100, 101, 102]
System.out.println(Files.mismatch(target, file4)); // 0

System.out.println(Arrays.toString(Files.readAllBytes(file5))); // []
System.out.println(Files.mismatch(target, file5)); // 0

final var ret = Files.readAllBytes(file6);
System.out.println(Arrays.toString(ret)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
System.out.println(Files.mismatch(target, file6)); // 3

static Path move (Path source, Path target, CopyOption... options)

Move or rename a file to a target file.

final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.writeString(source, "abcd");

System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a---      4 source.txt

System.out.println(Files.move(source, target)); // D:\java-work\target.txt

System.out.println(Files.exists(source)); // false
System.out.println(Files.exists(target)); // true

System.out.println(Files.readString(target)); // abcd

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a---      4 target.txt
final var source = Path.of("D:", "java-work", "source-dir");
System.out.println(source); // D:\java-work\source-dir

final var target = Path.of("D:", "java-work", "target-dir");
System.out.println(target); // D:\java-work\target-dir

Files.createDirectory(source);
Files.createFile(source.resolve(Path.of("aaa.txt")));
Files.createFile(source.resolve(Path.of("bbb.txt")));

System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─source-dir
//        aaa.txt
//        bbb.txt

System.out.println(Files.move(source, target)); // D:\java-work\target-dir

System.out.println(Files.exists(source)); // false
System.out.println(Files.exists(target)); // true

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─target-dir
//        aaa.txt
//        bbb.txt
final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

Files.createFile(source);
System.out.println(Files.exists(source)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt

System.out.println(Files.move(source, source)); // D:\java-work\source.txt

System.out.println(Files.exists(source)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

Files.createFile(source);
Files.createFile(target);

System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Name
//source.txt
//target.txt

try {
    Files.move(source, target);
} catch (FileAlreadyExistsException e) {
    System.out.println("FileAlreadyExistsException!");
}

// Result
// ↓
//FileAlreadyExistsException!
// An example of moving a file to a different FileStore.

final var source = Path.of("D:", "java-work", "source.txt");
System.out.println(source); // D:\java-work\source.txt

final var target = Path.of("R:", "java-work", "target.txt");
System.out.println(target); // R:\java-work\target.txt

Files.createFile(source);

System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

System.out.println(Files.move(source, target)); // R:\java-work\target.txt

System.out.println(Files.exists(source)); // false
System.out.println(Files.exists(target)); // true
// An example of moving a directory to a different FileStore.

final var source = Path.of("D:", "java-work", "source-dir");
System.out.println(source); // D:\java-work\source-dir

final var target = Path.of("R:", "java-work", "target-dir");
System.out.println(target); // R:\java-work\target-dir

Files.createDirectory(source);
Files.createFile(source.resolve(Path.of("aaa.txt")));

System.out.println(Files.exists(source)); // true
System.out.println(Files.exists(target)); // false

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─source-dir
//        aaa.txt

try {
    Files.move(source, target);
} catch (DirectoryNotEmptyException e) {
    System.out.println("DirectoryNotEmptyException!");
}

// Result
// ↓
//DirectoryNotEmptyException!

static BufferedReader newBufferedReader (Path path)

Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, """
        abcd
        XYZ
        12345
        """);

try (final var reader = Files.newBufferedReader(path)) {
    System.out.println(reader.readLine()); // abcd
    System.out.println(reader.readLine()); // XYZ
    System.out.println(reader.readLine()); // 12345
}

static BufferedReader newBufferedReader (Path path, Charset cs)

Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner.

Please see also : newBufferedReader(Path path)

final var utf8 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(utf8); // D:\java-work\aaa.txt

Files.writeString(utf8, "〇△□×", StandardCharsets.UTF_8);

try (final var reader = Files.newBufferedReader(utf8, StandardCharsets.UTF_8)) {
    System.out.println(reader.readLine()); // 〇△□×
}

try (final var reader = Files.newBufferedReader(utf8, Charset.forName("Shift_JIS"))) {
    reader.readLine();
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!
final var sjis = Path.of("D:", "java-work", "aaa.txt");
System.out.println(sjis); // D:\java-work\aaa.txt

Files.writeString(sjis, "〇△□×", Charset.forName("Shift_JIS"));

try (final var reader = Files.newBufferedReader(sjis, Charset.forName("Shift_JIS"))) {
    System.out.println(reader.readLine()); // 〇△□×
}

try (final var reader = Files.newBufferedReader(sjis, StandardCharsets.UTF_8)) {
    reader.readLine();
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static BufferedWriter newBufferedWriter (Path path, Charset cs, OpenOption... options)

Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.

Please see also : newBufferedWriter(Path path, OpenOption... options)

final var sjis = Path.of("D:", "java-work", "aaa.txt");
System.out.println(sjis); // D:\java-work\aaa.txt

try (final var writer = Files.newBufferedWriter(sjis, Charset.forName("Shift_JIS"))) {
    writer.write("〇△□×");
}

System.out.println(Files.readString(sjis, Charset.forName("Shift_JIS"))); // 〇△□×

try {
    Files.readString(sjis, StandardCharsets.UTF_8);
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static BufferedWriter newBufferedWriter (Path path, OpenOption... options)

Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

try (final var writer = Files.newBufferedWriter(path)) {
    writer.write("abcd");
    writer.newLine();

    writer.write("XYZ");
    writer.newLine();
}

final var str = Files.readString(path);
System.out.print(str);

// Result
// ↓
//abcd
//XYZ
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

try (final var writer = Files.newBufferedWriter(path)) {
    writer.write("abcd");
}

System.out.println(Files.readString(path)); // abcd

try (final var writer = Files.newBufferedWriter(path)) {
    writer.write("XYZ");
}

System.out.println(Files.readString(path)); // XYZ

try (final var writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) {
    writer.write("1234");
}

System.out.println(Files.readString(path)); // XYZ1234

static SeekableByteChannel newByteChannel (Path path, OpenOption... options)

Opens or creates a file, returning a seekable byte channel to access the file.

final var path = Path.of("D:", "java-work", "aaa.data");
System.out.println(path);
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

try (final var channel = Files.newByteChannel(path,
        StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
    final var src = ByteBuffer.wrap(new byte[]{10, 20, 30});
    System.out.println(Arrays.toString(src.array())); // [10, 20, 30]
    System.out.println(channel.write(src)); // 3
}

System.out.println(Arrays.toString(Files.readAllBytes(path))); // [10, 20, 30]

try (final var channel = Files.newByteChannel(path, StandardOpenOption.READ)) {
    final var dst = ByteBuffer.allocate(3);
    System.out.println(channel.read(dst)); // 3
    System.out.println(Arrays.toString(dst.array())); // [10, 20, 30]
}

static SeekableByteChannel newByteChannel (Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)

Opens or creates a file, returning a seekable byte channel to access the file.

Please see below links.

static DirectoryStream<Path> newDirectoryStream (Path dir)

Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.

final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//    aaa.txt
//    bbb.txt
//    ccc.txt

try (final var stream = Files.newDirectoryStream(dir)) {
    for (final var path : stream) {
        System.out.println(path);
    }
}

// Result
// ↓
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\ccc.txt
final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa1.txt
//│  aaa2.txt
//│
//└─dir
//        bbb1.txt
//        bbb2.txt

try (final var stream = Files.newDirectoryStream(dir)) {
    for (final var path : stream) {
        System.out.println(path);
    }
}

// Result
// ↓
//D:\java-work\aaa1.txt
//D:\java-work\aaa2.txt
//D:\java-work\dir
final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

System.out.println(Files.notExists(nonExistentPath)); // true

try (var _ = Files.newDirectoryStream(nonExistentPath)) {
    System.out.println("No errors");
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static DirectoryStream<Path> newDirectoryStream (Path dir, String glob)

Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.

Please see also : newDirectoryStream(Path dir)

final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//    aaa.txt
//    bbb.txt
//    Book.java
//    Page.java

try (final var stream = Files.newDirectoryStream(dir, "*")) {
    for (final var file : stream) {
        System.out.println(file);
    }
}

// Result
// ↓
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\Book.java
//D:\java-work\Page.java

try (final var stream = Files.newDirectoryStream(dir, "*.java")) {
    for (final var file : stream) {
        System.out.println(file);
    }
}

// Result
// ↓
//D:\java-work\Book.java
//D:\java-work\Page.java

try (final var stream = Files.newDirectoryStream(dir, "b*")) {
    for (final var file : stream) {
        System.out.println(file);
    }
}

// Result
// ↓
//D:\java-work\bbb.txt
//D:\java-work\Book.java

static DirectoryStream<Path> newDirectoryStream (Path dir, DirectoryStream.Filter<? super Path> filter)

Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.

Please see also : newDirectoryStream(Path dir)

final var dir = Path.of("D:", "java-work");
System.out.println(dir); // D:\java-work

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//    aaa.txt
//    bbb.txt
//    Book.java
//    Page.java

try (final var stream = Files.newDirectoryStream(dir, (_) -> true)) {
    for (final var path : stream) {
        System.out.println(path);
    }
}

// Result
// ↓
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\Book.java
//D:\java-work\Page.java

try (final var stream = Files.newDirectoryStream(dir, (path) -> path.toString().endsWith(".java"))) {
    for (final var path : stream) {
        System.out.println(path);
    }
}

// Result
// ↓
//D:\java-work\Book.java
//D:\java-work\Page.java

static InputStream newInputStream (Path path, OpenOption... options)

Opens a file, returning an input stream to read from the file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.write(path, new byte[]{10, 20, 30});

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

try (final var inputStream = Files.newInputStream(path)) {
    final var bytes = inputStream.readAllBytes();
    System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
}
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.write(target, new byte[]{10, 20, 30});
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        3 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

try (final var inputStream = Files.newInputStream(target)) {
    final var bytes = inputStream.readAllBytes();
    System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
}

try (final var inputStream = Files.newInputStream(link)) {
    final var bytes = inputStream.readAllBytes();
    System.out.println(Arrays.toString(bytes)); // [10, 20, 30]
}

try (var _ = Files.newInputStream(link, LinkOption.NOFOLLOW_LINKS)) {
    System.out.println("No errors");
} catch (IOException e) {
    System.out.println(e);
}

// Result
// ↓
//java.io.IOException: File is symbolic link

static OutputStream newOutputStream (Path path, OpenOption... options)

Opens or creates a file, returning an output stream that may be used to write bytes to the file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

try (final var outputStream = Files.newOutputStream(path)) {
    outputStream.write(10);
    outputStream.write(20);
    outputStream.write(new byte[]{30, 40, 50});
}

final var bytes = Files.readAllBytes(path);
System.out.println(Arrays.toString(bytes)); // [10, 20, 30, 40, 50]
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

try (final var outputStream = Files.newOutputStream(path)) {
    outputStream.write(10);
    outputStream.write(20);
}

System.out.println(Arrays.toString(Files.readAllBytes(path))); // [10, 20]

try (final var outputStream = Files.newOutputStream(path)) {
    outputStream.write(30);
    outputStream.write(40);
}

System.out.println(Arrays.toString(Files.readAllBytes(path))); // [30, 40]

try (final var outputStream = Files.newOutputStream(
        path, StandardOpenOption.APPEND)) {
    outputStream.write(50);
    outputStream.write(60);
}

System.out.println(Arrays.toString(Files.readAllBytes(path))); // [30, 40, 50, 60]

static boolean notExists (Path path, LinkOption... options)

Tests whether the file located by this path does not exist.

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

final var file = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx

Files.createDirectory(dir);
Files.createFile(file);
Files.createSymbolicLink(link, nonExistentPath);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//-a---  ...        0 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\xxx

System.out.println(Files.isDirectory(dir)); // true
System.out.println(Files.notExists(dir)); // false

System.out.println(Files.isRegularFile(file)); // true
System.out.println(Files.notExists(file)); // false

System.out.println(Files.isSymbolicLink(link)); // true
System.out.println(Files.notExists(link)); // true
System.out.println(Files.notExists(link, LinkOption.NOFOLLOW_LINKS)); // false

System.out.println(Files.notExists(nonExistentPath)); // true

static String probeContentType (Path path)

Probes the content type of a file.

// --- PowerShell ---
//PS D:\java-work> ls -Name
//image.png
//index.html
//text.txt
//unknown.abc

final var imageFile = Path.of("D:", "java-work", "image.png");
System.out.println(Files.probeContentType(imageFile)); // "image/png"

final var htmlFile = Path.of("D:", "java-work", "index.html");
System.out.println(Files.probeContentType(htmlFile)); // "text/html"

final var textFile = Path.of("D:", "java-work", "text.txt");
System.out.println(Files.probeContentType(textFile)); // "text/plain"

final var unknownFile = Path.of("D:", "java-work", "unknown.abc");
System.out.println(Files.probeContentType(unknownFile)); // null

static byte[] readAllBytes (Path path)

Reads all the bytes from a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.write(path, new byte[]{10, 20, 30});

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

final var ret = Files.readAllBytes(path);
System.out.println(Arrays.toString(ret)); // [10, 20, 30]

static List<String> readAllLines (Path path)

Read all lines from a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, """
        abcd
        XYZ
        12345
        """);

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

final var ret = Files.readAllLines(path);
System.out.println(ret); // [abcd, XYZ, 12345]

static List<String> readAllLines (Path path, Charset cs)

Read all lines from a file.

Please see also : readAllLines(Path path)

final var utf8 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(utf8); // D:\java-work\aaa.txt

Files.writeString(utf8, """
        abcd
        〇△□×
        """, StandardCharsets.UTF_8);

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

final var lines = Files.readAllLines(utf8, StandardCharsets.UTF_8);
System.out.println(lines); // [abcd, 〇△□×]

try {
    Files.readAllLines(utf8, Charset.forName("Shift_JIS"));
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!
final var sjis = Path.of("D:", "java-work", "aaa.txt");
System.out.println(sjis); // D:\java-work\aaa.txt

Files.writeString(sjis, """
        abcd
        〇△□×
        """, Charset.forName("Shift_JIS"));

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

final var lines = Files.readAllLines(sjis, Charset.forName("Shift_JIS"));
System.out.println(lines); // [abcd, 〇△□×]

try {
    Files.readAllLines(sjis, StandardCharsets.UTF_8);
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static <A extends BasicFileAttributes> A readAttributes (Path path, Class<A> type, LinkOption... options)

Reads a file's attributes as a bulk operation.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, "abcd");

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Length, Name
//
//Mode  Length Name
//----  ------ ----
//-a---      4 aaa.txt

final var attrs = Files.readAttributes(path, BasicFileAttributes.class);

System.out.println(attrs.isDirectory()); // false
System.out.println(attrs.isRegularFile()); // true
System.out.println(attrs.size()); // 4
final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

Files.createDirectory(dir);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir

final var attrs = Files.readAttributes(dir, BasicFileAttributes.class);

System.out.println(attrs.isDirectory()); // true
System.out.println(attrs.isRegularFile()); // false
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(target);
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        0 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

final var attrs1 = Files.readAttributes(link, BasicFileAttributes.class);
System.out.println(attrs1.isSymbolicLink()); // false

final var attrs2 = Files.readAttributes(link,
        BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
System.out.println(attrs2.isSymbolicLink()); // true
final var readOnlyFile = Path.of("D:", "java-work", "read-only.txt");
System.out.println(readOnlyFile); // D:\java-work\read-only.txt

final var hiddenFile = Path.of("D:", "java-work", "hidden.txt");
System.out.println(hiddenFile); // D:\java-work\hidden.txt

Files.createFile(readOnlyFile);
Files.setAttribute(readOnlyFile, "dos:readonly", true);

Files.createFile(hiddenFile);
Files.setAttribute(hiddenFile, "dos:hidden", true);

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a-h- hidden.txt
//-ar-- read-only.txt

final var attrs1 = Files.readAttributes(readOnlyFile, DosFileAttributes.class);

System.out.println(attrs1.isHidden()); // false
System.out.println(attrs1.isReadOnly()); // true

final var attrs2 = Files.readAttributes(hiddenFile, DosFileAttributes.class);

System.out.println(attrs2.isHidden()); // true
System.out.println(attrs2.isReadOnly()); // false

static Map<String,Object> readAttributes (Path path, String attributes, LinkOption... options)

Reads a set of file attributes as a bulk operation.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a--- aaa.txt

final var file = Path.of("D:", "java-work", "aaa.txt");
final var attrs = Files.readAttributes(file, "*");

//{lastAccessTime=2024-10-19T07:19:25.3063571Z,
// lastModifiedTime=2024-10-19T07:19:25.3063571Z,
// size=0, creationTime=2024-10-19T07:14:47.356487Z,
// isSymbolicLink=false, isRegularFile=true, fileKey=null,
// isOther=false, isDirectory=false}
System.out.println(attrs);
final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir

Files.createDirectory(dir);

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir

final var attrs = Files.readAttributes(dir, "isRegularFile,isDirectory");
System.out.println(attrs); // {isRegularFile=false, isDirectory=true}
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(target);
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...        0 aaa.txt
//la---  ...        0 link.txt -> D:\java-work\aaa.txt

final var attrs1 = Files.readAttributes(link, "isRegularFile,isSymbolicLink");
System.out.println(attrs1); // {isSymbolicLink=false, isRegularFile=true}

final var attrs2 = Files.readAttributes(link,
        "isRegularFile,isSymbolicLink", LinkOption.NOFOLLOW_LINKS);
System.out.println(attrs2); // {isSymbolicLink=true, isRegularFile=false}
final var readOnlyFile = Path.of("D:", "java-work", "read-only.txt");
System.out.println(readOnlyFile); // D:\java-work\read-only.txt

final var hiddenFile = Path.of("D:", "java-work", "hidden.txt");
System.out.println(hiddenFile); // D:\java-work\hidden.txt

Files.createFile(readOnlyFile);
Files.setAttribute(readOnlyFile, "dos:readonly", true);

Files.createFile(hiddenFile);
Files.setAttribute(hiddenFile, "dos:hidden", true);

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a-h- hidden.txt
//-ar-- read-only.txt

final var attrs1 = Files.readAttributes(
        readOnlyFile, "dos:isRegularFile,hidden,readonly");
System.out.println(attrs1); // {readonly=true, hidden=false, isRegularFile=true}

final var attrs2 = Files.readAttributes(
        hiddenFile, "dos:isRegularFile,hidden,readonly");
System.out.println(attrs2); // {readonly=false, hidden=true, isRegularFile=true}

static String readString (Path path)

Reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, """
        abcd
        XYZ
        12345
        """);

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

final var ret = Files.readString(path);
System.out.println(ret);

// Result
// ↓
//abcd
//XYZ
//12345

static String readString (Path path, Charset cs)

Reads all characters from a file into a string, decoding from bytes to characters using the specified charset.

Please see also : readString(Path path)

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.writeString(path, "〇△□×", Charset.forName("Shift_JIS"));

// --- PowerShell ---
//PS D:\java-work> ls -Name
//aaa.txt

System.out.println(Files.readString(path, Charset.forName("Shift_JIS"))); // 〇△□×

try {
    Files.readString(path, StandardCharsets.UTF_8);
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static Path readSymbolicLink (Path link)

Reads the target of a symbolic link (optional operation).

final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(target);
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt
//-a---  ...        0 target.txt

System.out.println(Files.isRegularFile(link)); // true
System.out.println(Files.isSymbolicLink(link)); // true
System.out.println(Files.readSymbolicLink(link)); // aaa.txt

try {
    System.out.println(Files.isRegularFile(target)); // true
    System.out.println(Files.isSymbolicLink(target)); // false
    Files.readSymbolicLink(target);

} catch (NotLinkException e) {
    System.out.println("NotLinkException!");
}

// Result
// ↓
//NotLinkException!

static Path setAttribute (Path path, String attribute, Object value, LinkOption... options)

Sets the value of a file attribute.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);
System.out.println(Files.isHidden(path)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a--- aaa.txt

Files.setAttribute(path, "dos:hidden", true);
System.out.println(Files.isHidden(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a-h- aaa.txt
final var target = Path.of("D:", "java-work", "target.txt");
System.out.println(target); // D:\java-work\target.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createFile(target);
Files.createSymbolicLink(link, target);

System.out.println(Files.isHidden(target)); // false

// --- PowerShell ---
//PS D:\java-work> ls -Force
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt
//-a---  ...        0 target.txt

Files.setAttribute(link, "dos:hidden", true);
System.out.println(Files.isHidden(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Force
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la---  ...        0 link.txt -> D:\java-work\target.txt
//-a-h-  ...        0 target.txt

Files.setAttribute(link, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
System.out.println(Files.isHidden(target)); // true

// --- PowerShell ---
//PS D:\java-work> ls -Force
//...
//Mode   ...   Length Name
//----   ...   ------ ----
//la-h-  ...        0 link.txt -> D:\java-work\target.txt
//-a-h-  ...        0 target.txt

static Path setLastModifiedTime (Path path, FileTime time)

Updates a file's last modified time attribute.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var ret = Files.setLastModifiedTime(path, FileTime.from(
        ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId).toInstant()));
System.out.println(ret); // D:\java-work\aaa.txt

// --- PowerShell ---
//PS D:\java-work> ls | Format-Table -Property LastWriteTime, Name
//
//LastWriteTime      Name
//-------------      ----
//2100/01/01 0:00:00 aaa.txt

// FileTime is UTC.
final var fileTime = Files.getLastModifiedTime(path);
System.out.println(fileTime); // 2099-12-31T15:00:00Z

final var zonedDateTime = ZonedDateTime.ofInstant(fileTime.toInstant(), zoneId);
System.out.println(zonedDateTime); // 2100-01-01T00:00+09:00[Asia/Tokyo]
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var zonedDateTime = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId);
System.out.println(zonedDateTime); // 2100-01-01T00:00+09:00[Asia/Tokyo]

Files.createFile(target);
Files.setLastModifiedTime(target, FileTime.from(zonedDateTime.toInstant()));

Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2100/01/01     0:00              0 aaa.txt
//la---          2024/10/19    16:31              0 link.txt -> D:\java-work\aaa.txt

final var ret1 = Files.getLastModifiedTime(link);
System.out.println(ret1); // 2099-12-31T15:00:00Z

final var ret2 = Files.getLastModifiedTime(link, LinkOption.NOFOLLOW_LINKS);
System.out.println(ret2); // 2024-10-19T07:31:55.9393338Z

static Path setOwner (Path path, UserPrincipal owner)

Updates the file owner.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt

Files.createFile(path);

final var service = path.getFileSystem().getUserPrincipalLookupService();
final var newOwner = service.lookupPrincipalByName("test-user");

final var ret1 = Files.setOwner(path, newOwner);
System.out.println(ret1); // D:\java-work\aaa.txt

// --- PowerShell ---
//PS D:\java-work> Get-Acl .\aaa.txt
//...
//Path    Owner           Access
//----    -----           ------
//aaa.txt MY-PC\test-user BUILTIN\Administrators Allow  FullControl…

final var ret2 = Files.getOwner(path);
System.out.println(ret2); // MY-PC\test-user (User)
final var target = Path.of("D:", "java-work", "aaa.txt");
System.out.println(target); // D:\java-work\aaa.txt

final var link = Path.of("D:", "java-work", "link.txt");
System.out.println(link); // D:\java-work\link.txt

Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls | Get-Acl
//..
//Path     Owner                    Access
//----     -----                    ------
//aaa.txt  MY-PC\test-user          BUILTIN\Administrators Allow  FullControl…
//link.txt BUILTIN\Administrators   BUILTIN\Administrators Allow  FullControl…

final var ret1 = Files.getOwner(link);
System.out.println(ret1); // MY-PC\test-user (User)

final var ret2 = Files.getOwner(link, LinkOption.NOFOLLOW_LINKS);
System.out.println(ret2); // BUILTIN\Administrators (Alias)

static Path setPosixFilePermissions (Path path, Set<PosixFilePermission> perms)

Sets a file's POSIX permissions.

The following code runs on Linux.

System.out.println(System.getProperty("os.name")); // Linux

// --- Linux Terminal ---
//$ ls -l sample.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample.sh

final var path = Path.of("sample.sh");

final var permissions = Files.getPosixFilePermissions(path);
System.out.println(PosixFilePermissions.toString(permissions)); // rw-rw-r--

final var newPermissions = PosixFilePermissions.fromString("rwxr-xr--");

final var ret = Files.setPosixFilePermissions(path, newPermissions);
System.out.println(ret); // sample.sh

// --- Linux Terminal ---
//$ ls -l sample.sh
//-rwxr-xr-- 1 xxxx xxxx 0 ... sample.sh

static long size (Path path)

Returns the size of a file (in bytes).

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//└─dir
//        ccc.txt
//
//PS D:\java-work> ls -Recurse
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//-a---  ...        5 aaa.txt
//-a---  ...     1000 bbb.txt
//
//    Directory: D:\java-work\dir
//
//Mode   ...   Length Name
//----   ...   ------ ----
//-a---  ...       12 ccc.txt


final var file1 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(file1); // D:\java-work\aaa.txt
System.out.println(Files.size(file1)); // 5

final var file2 = Path.of("D:", "java-work", "bbb.txt");
System.out.println(file2); // D:\java-work\bbb.txt
System.out.println(Files.size(file2)); // 1000

final var dir = Path.of("D:", "java-work", "dir");
System.out.println(dir); // D:\java-work\dir
System.out.println(Files.size(dir)); // 0
final var nonExistentPath = Path.of("D:", "java-work", "xxx");
System.out.println(nonExistentPath); // D:\java-work\xxx
System.out.println(Files.notExists(nonExistentPath)); // true

try {
    Files.size(nonExistentPath);
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Stream<Path> walk (Path start, int maxDepth, FileVisitOption... options)

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

Please see also : walk(Path start, FileVisitOption... options)

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

System.out.println("maxDepth : 3");
try (final var stream = Files.walk(start, 3)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 3
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2
//D:\java-work\dir1\dir1-2\eee.txt
//D:\java-work\dir1\dir1-2\fff.txt
//D:\java-work\dir2
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt

System.out.println("maxDepth : 2");
try (final var stream = Files.walk(start, 2)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 2
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2
//D:\java-work\dir2
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt

System.out.println("maxDepth : 1");
try (final var stream = Files.walk(start, 1)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 1
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir2

System.out.println("maxDepth : 0");
try (final var stream = Files.walk(start, 0)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//maxDepth : 0
//D:\java-work

static Stream<Path> walk (Path start, FileVisitOption... options)

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

try (final var stream = Files.walk(start)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//D:\java-work
//D:\java-work\aaa.txt
//D:\java-work\bbb.txt
//D:\java-work\dir1
//D:\java-work\dir1\ccc.txt
//D:\java-work\dir1\ddd.txt
//D:\java-work\dir1\dir1-2
//D:\java-work\dir1\dir1-2\eee.txt
//D:\java-work\dir1\dir1-2\fff.txt
//D:\java-work\dir2
//D:\java-work\dir2\ggg.txt
//D:\java-work\dir2\hhh.txt
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//├─dir
//│      aaa.txt
//│      bbb.txt
//│
//└─link-dir
//        aaa.txt
//        bbb.txt
//
//PS D:\java-work> ls
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//l----  ...          link-dir -> D:\java-work\dir

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

try (final var stream = Files.walk(start)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//D:\java-work\link-dir

System.out.println("FileVisitOption : FOLLOW_LINKS");
try (final var stream = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//FileVisitOption : FOLLOW_LINKS
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//D:\java-work\link-dir
//D:\java-work\link-dir\aaa.txt
//D:\java-work\link-dir\bbb.txt
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─dir
//    │  aaa.txt
//    │  bbb.txt
//    │
//    └─link-parent-dir
//        │  aaa.txt
//        │  bbb.txt
//        │
//        └─link-parent-dir
//            │  aaa.txt
//            │  bbb.txt
// ...

// --- PowerShell ---
//PS D:\java-work> ls -Recurse
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//
//    Directory: D:\java-work\dir
//
//Mode   ...   Length Name
//----   ...   ------ ----
//l----  ...          link-parent-dir -> D:\java-work\dir
//-a---  ...        0 aaa.txt
//-a---  ...        0 bbb.txt

// Symbolic links are circular.

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

try (final var stream = Files.walk(start)) {
    stream.forEach(System.out::println);
}

// Result
// ↓
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//D:\java-work\dir\link-parent-dir

System.out.println("FileVisitOption : FOLLOW_LINKS");
try (final var stream = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
    stream.forEach(System.out::println);
} catch (UncheckedIOException e) {
    System.out.println(e);
}

// Result
// ↓
//FileVisitOption : FOLLOW_LINKS
//D:\java-work
//D:\java-work\dir
//D:\java-work\dir\aaa.txt
//D:\java-work\dir\bbb.txt
//java.io.UncheckedIOException: java.nio.file.FileSystemLoopException
final var start = Path.of("D:", "java-work", "xxx");
System.out.println(start); // D:\java-work\xxx
System.out.println(Files.notExists(start)); // true

try (var _ = Files.walk(start)) {
    System.out.println("No errors");
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// Result
// ↓
//NoSuchFileException!

static Path walkFileTree (Path start, FileVisitor<? super Path> visitor)

Walks a file tree.

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

System.out.println("-- start --");
final var ret1 = Files.walkFileTree(start, new FileVisitor<>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
});

System.out.println("ret : " + ret1);

// Result
// ↓
//-- start --
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//visitFile : D:\java-work\bbb.txt
//preVisitDirectory : D:\java-work\dir1
//visitFile : D:\java-work\dir1\ccc.txt
//visitFile : D:\java-work\dir1\ddd.txt
//preVisitDirectory : D:\java-work\dir1\dir1-2
//visitFile : D:\java-work\dir1\dir1-2\eee.txt
//visitFile : D:\java-work\dir1\dir1-2\fff.txt
//postVisitDirectory : D:\java-work\dir1\dir1-2
//postVisitDirectory : D:\java-work\dir1
//preVisitDirectory : D:\java-work\dir2
//visitFile : D:\java-work\dir2\ggg.txt
//visitFile : D:\java-work\dir2\hhh.txt
//postVisitDirectory : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("-- start --");
final var ret2 = Files.walkFileTree(start, new FileVisitor<>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        if (Path.of("D:", "java-work", "aaa.txt").equals(file)) {
            return FileVisitResult.SKIP_SIBLINGS;
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
});

System.out.println("ret : " + ret2);

// Result
// ↓
//-- start --
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("-- start --");
final var ret3 = Files.walkFileTree(start, new FileVisitor<>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        if (Path.of("D:", "java-work", "dir1").equals(dir)) {
            return FileVisitResult.SKIP_SUBTREE;
        }

        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
});

System.out.println("ret : " + ret3);

// Result
// ↓
//-- start --
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//visitFile : D:\java-work\bbb.txt
//preVisitDirectory : D:\java-work\dir1
//preVisitDirectory : D:\java-work\dir2
//visitFile : D:\java-work\dir2\ggg.txt
//visitFile : D:\java-work\dir2\hhh.txt
//postVisitDirectory : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//├─dir1
//└─dir2
//        aaa.txt
//
//PS D:\java-work> ls | Get-Acl
//...
//Path Owner           Access
//---- -----           ------
//dir1 MY-PC\test-user BUILTIN\Administrators Deny  ReadData…
//dir2 MY-PC\test-user BUILTIN\Administrators Allow  FullControl…

// Intentional errors.

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

System.out.println("-- start --");
final var ret = Files.walkFileTree(start, new FileVisitor<>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
});

System.out.println("ret : " + ret);

// Result
// ↓
//-- start --
//preVisitDirectory : D:\java-work
//visitFileFailed : D:\java-work\dir1
//preVisitDirectory : D:\java-work\dir2
//visitFile : D:\java-work\dir2\aaa.txt
//postVisitDirectory : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work

static Path walkFileTree (Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor)

Walks a file tree.

Please see also : walkFileTree(Path start, FileVisitor<? super Path> visitor)

// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//│  aaa.txt
//│  bbb.txt
//│
//├─dir1
//│  │  ccc.txt
//│  │  ddd.txt
//│  │
//│  └─dir1-2
//│          eee.txt
//│          fff.txt
//│
//└─dir2
//        ggg.txt
//        hhh.txt

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

final var visitor = new FileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
};

System.out.println("maxDepth : 3");
final var ret1 = Files.walkFileTree(start, Collections.emptySet(), 3, visitor);
System.out.println("ret : " + ret1);

// Result
// ↓
//maxDepth : 3
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//visitFile : D:\java-work\bbb.txt
//preVisitDirectory : D:\java-work\dir1
//visitFile : D:\java-work\dir1\ccc.txt
//visitFile : D:\java-work\dir1\ddd.txt
//preVisitDirectory : D:\java-work\dir1\dir1-2
//visitFile : D:\java-work\dir1\dir1-2\eee.txt
//visitFile : D:\java-work\dir1\dir1-2\fff.txt
//postVisitDirectory : D:\java-work\dir1\dir1-2
//postVisitDirectory : D:\java-work\dir1
//preVisitDirectory : D:\java-work\dir2
//visitFile : D:\java-work\dir2\ggg.txt
//visitFile : D:\java-work\dir2\hhh.txt
//postVisitDirectory : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("maxDepth : 2");
final var ret2 = Files.walkFileTree(start, Collections.emptySet(), 2, visitor);
System.out.println("ret : " + ret2);

// Result
// ↓
//maxDepth : 2
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//visitFile : D:\java-work\bbb.txt
//preVisitDirectory : D:\java-work\dir1
//visitFile : D:\java-work\dir1\ccc.txt
//visitFile : D:\java-work\dir1\ddd.txt
//visitFile : D:\java-work\dir1\dir1-2
//postVisitDirectory : D:\java-work\dir1
//preVisitDirectory : D:\java-work\dir2
//visitFile : D:\java-work\dir2\ggg.txt
//visitFile : D:\java-work\dir2\hhh.txt
//postVisitDirectory : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("maxDepth : 1");
final var ret3 = Files.walkFileTree(start, Collections.emptySet(), 1, visitor);
System.out.println("ret : " + ret3);

// Result
// ↓
//maxDepth : 1
//preVisitDirectory : D:\java-work
//visitFile : D:\java-work\aaa.txt
//visitFile : D:\java-work\bbb.txt
//visitFile : D:\java-work\dir1
//visitFile : D:\java-work\dir2
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("maxDepth : 0");
final var ret = Files.walkFileTree(start, Collections.emptySet(), 0, visitor);
System.out.println("ret : " + ret);

// Result
// ↓
//maxDepth : 0
//visitFile : D:\java-work
//ret : D:\java-work
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//├─dir
//│      aaa.txt
//│      bbb.txt
//│
//└─link-dir
//        aaa.txt
//        bbb.txt
//
//PS D:\java-work> ls
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ------ ----
//d----  ...          dir
//l----  ...          link-dir -> D:\java-work\dir

final var start = Path.of("D:", "java-work");
System.out.println(start); // D:\java-work

final var visitor = new FileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
};

final var ret1 = Files.walkFileTree(
        start, Collections.emptySet(), Integer.MAX_VALUE, visitor);
System.out.println("ret : " + ret1);

// Result
// ↓
//preVisitDirectory : D:\java-work
//preVisitDirectory : D:\java-work\dir
//visitFile : D:\java-work\dir\aaa.txt
//visitFile : D:\java-work\dir\bbb.txt
//postVisitDirectory : D:\java-work\dir
//visitFile : D:\java-work\link-dir
//postVisitDirectory : D:\java-work
//ret : D:\java-work

System.out.println("FileVisitOption : FOLLOW_LINKS");
final var ret2 = Files.walkFileTree(
        start, Set.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, visitor);
System.out.println("ret : " + ret2);

// Result
// ↓
//FileVisitOption : FOLLOW_LINKS
//preVisitDirectory : D:\java-work
//preVisitDirectory : D:\java-work\dir
//visitFile : D:\java-work\dir\aaa.txt
//visitFile : D:\java-work\dir\bbb.txt
//postVisitDirectory : D:\java-work\dir
//preVisitDirectory : D:\java-work\link-dir
//visitFile : D:\java-work\link-dir\aaa.txt
//visitFile : D:\java-work\link-dir\bbb.txt
//postVisitDirectory : D:\java-work\link-dir
//postVisitDirectory : D:\java-work
//ret : D:\java-work
// --- PowerShell ---
//PS D:\java-work> tree /F
//...
//D:.
//└─dir
//    │  aaa.txt
//    │  bbb.txt
//    │
//    └─link-parent-dir
//        │  aaa.txt
//        │  bbb.txt
//        │
//        └─link-parent-dir
//            │  aaa.txt
//            │  bbb.txt
// ...

// --- PowerShell ---
//PS D:\java-work> ls -Recurse
//
//    Directory: D:\java-work
//
//Mode   ...   Length Name
//----   ...   ----- ----
//d----  ...         dir
//
//    Directory: D:\java-work\dir
//
//Mode   ...   Length Name
//----   ...   ------ ----
//l----  ...          link-parent-dir -> D:\java-work\dir
//-a---  ...        0 aaa.txt
//-a---  ...        0 bbb.txt

// Symbolic links are circular.

final var start = Path.of("D:", "java-work");
System.out.println(start);

final var visitor = new FileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        System.out.println("preVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("visitFile : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.out.println("visitFileFailed : " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        System.out.println("postVisitDirectory : " + dir);
        return FileVisitResult.CONTINUE;
    }
};

final var ret = Files.walkFileTree(start,
        Set.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, visitor);
System.out.println("ret : " + ret);

// Result
// ↓
//preVisitDirectory : D:\java-work
//preVisitDirectory : D:\java-work\dir
//visitFile : D:\java-work\dir\aaa.txt
//visitFile : D:\java-work\dir\bbb.txt
//visitFileFailed : D:\java-work\dir\link-parent-dir
//postVisitDirectory : D:\java-work\dir
//postVisitDirectory : D:\java-work
//ret : D:\java-work

static Path write (Path path, byte[] bytes, OpenOption... options)

Writes bytes to a file.

final var path = Path.of("D:", "java-work", "aaa.data");
System.out.println(path); // D:\java-work\aaa.data
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final byte[] bytes1 = {0, 1, 2};
System.out.println(Files.write(path, bytes1)); // D:\java-work\aaa.data
System.out.println(Arrays.toString(Files.readAllBytes(path))); // [0, 1, 2]

final byte[] bytes2 = {3, 4, 5};
System.out.println(Files.write(path, bytes2)); // D:\java-work\aaa.data
System.out.println(Arrays.toString(Files.readAllBytes(path))); // [3, 4, 5]

final byte[] bytes3 = {6, 7, 8};
System.out.println(Files.write(
        path, bytes3, StandardOpenOption.APPEND)); // D:\java-work\aaa.data
System.out.println(Arrays.toString(Files.readAllBytes(path))); // [3, 4, 5, 6, 7, 8]

static Path write (Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options)

Write lines of text to a file.

Please see also : write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)

final var sjis = Path.of("D:", "java-work", "aaa.txt");
System.out.println(sjis); // D:\java-work\aaa.txt
System.out.println(Files.notExists(sjis)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var ret1 = Files.write(sjis, List.of("〇", "△", "□"), Charset.forName("Shift_JIS"));
System.out.println(ret1); // D:\java-work\aaa.txt
System.out.println(Files.readAllLines(sjis, Charset.forName("Shift_JIS"))); // [〇, △, □]

try {
    Files.readAllLines(sjis, StandardCharsets.UTF_8);
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static Path write (Path path, Iterable<? extends CharSequence> lines, OpenOption... options)

Write lines of text to a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var ret1 = Files.write(path, List.of("aaa", "bbb", "ccc"));
System.out.println(ret1); // D:\java-work\aaa.txt
System.out.println(Files.readAllLines(path)); // [aaa, bbb, ccc]

final var ret2 = Files.write(path, List.of("ddd", "eee", "fff"));
System.out.println(ret2); // D:\java-work\aaa.txt
System.out.println(Files.readAllLines(path)); // [ddd, eee, fff]

final var ret3 = Files.write(path,
        List.of("XXX", "YYY", "ZZZ"), StandardOpenOption.APPEND);
System.out.println(ret3); // D:\java-work\aaa.txt
System.out.println(Files.readAllLines(path)); // // [ddd, eee, fff, XXX, YYY, ZZZ]

static Path writeString (Path path, CharSequence csq, Charset cs, OpenOption... options)

Write a CharSequence to a file.

Please see also : writeString(Path path, CharSequence csq, OpenOption... options)

final var sjis = Path.of("D:", "java-work", "aaa.txt");
System.out.println(sjis); // D:\java-work\aaa.txt
System.out.println(Files.notExists(sjis)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var ret = Files.writeString(sjis, "〇△□×", Charset.forName("Shift_JIS"));
System.out.println(ret); // D:\java-work\aaa.txt
System.out.println(Files.readString(sjis, Charset.forName("Shift_JIS"))); // 〇△□×

try {
    Files.readString(sjis, StandardCharsets.UTF_8);
} catch (MalformedInputException e) {
    System.out.println("MalformedInputException!");
}

// Result
// ↓
//MalformedInputException!

static Path writeString (Path path, CharSequence csq, OpenOption... options)

Write a CharSequence to a file.

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var ret1 = Files.writeString(path, "abc");
System.out.println(ret1); // D:\java-work\aaa.txt
System.out.println(Files.readString(path)); // abc

final var ret2 = Files.writeString(path, "def");
System.out.println(ret2); // D:\java-work\aaa.txt
System.out.println(Files.readString(path)); // def

final var ret3 = Files.writeString(path, "XYZ", StandardOpenOption.APPEND);
System.out.println(ret3); // D:\java-work\aaa.txt
System.out.println(Files.readString(path)); // defXYZ
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // D:\java-work\aaa.txt
System.out.println(Files.notExists(path)); // true

// --- PowerShell ---
//PS D:\java-work> ls
//<No files / directories>

final var csq = """
        abcd
        XYZ
        12345
        """;

final var ret = Files.writeString(path, csq);
System.out.println(ret); // D:\java-work\aaa.txt
System.out.println(Files.readAllLines(path)); // [abcd, XYZ, 12345]

Related posts

To top of page