Java : Files (ファイル操作) - API使用例

Files (Java SE 17 & JDK 17) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。


概要

このクラスは、ファイル、ディレクトリ、またはその他の種類のファイルを操作するstaticメソッドだけで構成されます。

クラス構成

Filesクラスには、

  • ファイルの読み書き、コピー、削除
  • ディレクトリの作成、削除

などなど、実際のファイルやディレクトリへアクセスするためのメソッドが数多くそろっています。

具体的なアクセス対象を指定するには Pathインタフェースを使います。

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
//<ファイル・ディレクトリなし>

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---          2022/04/21    13:48              4 aaa.txt

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

// --- PowerShell ---
//PS D:\java-work> ls
//<ファイル・ディレクトリなし>

関連記事:ファイル操作の基本

注意

  • 基本はWindows 10で実行した結果となります。
  • 一部 POSIX 環境でないと確認できないものは、Linuxで実行しています。

メソッド

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

すべてのバイトを入力ストリームからファイルにコピーします。

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 = new URL("https://example.com");
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
//<ファイル・ディレクトリなし>

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

// 結果
// ↓
//<!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!");
}

// 結果
// ↓
//FileAlreadyExistsException!

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

// 結果
// ↓
//[10, 20, 30]

static long copy (Path source, OutputStream out)

すべてのバイトをファイルから出力ストリームにコピーします。

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
//<ファイル・ディレクトリなし>

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

// 結果
// ↓
//NoSuchFileException!

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

ファイルをターゲット・ファイルにコピーします。

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!");
}

// 結果
// ↓
//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
//<ファイル・ディレクトリなし>

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

// 結果
// ↓
//NoSuchFileException!

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

存在しないすべての親ディレクトリをまず作成することで、ディレクトリを作成します。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

// --- 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!");
}

// 結果
// ↓
//FileAlreadyExistsException!

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

新しいディレクトリを作成します。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

// --- 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!");
}

// 結果
// ↓
//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!");
}

// 結果
// ↓
//NoSuchFileException!

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

新しい空のファイルを作成し、ファイルがすでに存在する場合は失敗します。

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
//<ファイル・ディレクトリなし>

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!");
}

// 結果
// ↓
//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
//<ファイル・ディレクトリなし>

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

// 結果
// ↓
//NoSuchFileException!

※FileAttributeを使うために、以下のコード例は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  9月 24 19:17 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  9月 24 19:17 sample2.txt

static Path createLink (Path link, Path existing)

既存のファイルに対して新しいリンク(ディレクトリ・エントリ)を作成します(オプションの操作)。

※Windowsではハード・リンクとして作成されます。

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
//<ファイル・ディレクトリなし>

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!");
}

// 結果
// ↓
//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!");
}

// 結果
// ↓
//FileAlreadyExistsException!

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

ターゲットへのシンボリック・リンクを作成します(オプションの操作)。

シンボリック・リンクの作成には管理者権限を必要とする場合があります。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/21    15:21              0 link.txt -> D:\java-work\target.txt
//-a---          2022/04/21    15:21              3 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
//<ファイル・ディレクトリなし>

// 実体のないリンクも作成可能です。
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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/21    15:25              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!");
}

// 結果
// ↓
//FileAlreadyExistsException!

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

デフォルトの一時ファイル・ディレクトリで新しいディレクトリを生成し、その名前には、指定された接頭辞が使用されます。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

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)

指定されたディレクトリで新しいディレクトリを生成し、その名前には、指定された接頭辞が使用されます。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

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)

指定された接頭辞と接尾辞をファイル名の生成に使用して、デフォルトの一時ファイル・ディレクトリに空のファイルを生成します。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

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)

指定されたディレクトリで新しい空のファイルを生成し、その名前には、指定された接頭辞および接尾辞の文字列が使用されます。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

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)

ファイルを削除します。

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
//<ファイル・ディレクトリなし>
// --- PowerShell ---
//PS D:\java-work> ls
//<ファイル・ディレクトリなし>

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!");
}

// 結果
// ↓
//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!");
}

// 結果
// ↓
//DirectoryNotEmptyException!

static boolean deleteIfExists (Path path)

ファイルが存在する場合は削除します。

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
//<ファイル・ディレクトリなし>

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

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

ファイルが存在するかどうかをテストします。

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

// 意図的にリンク先のファイルが存在しない状態にします。
Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/14    19:09              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)

指定された開始ファイルをルートとするファイル・ツリー内でファイルを検索することで Pathが遅延設定されるStreamを返します。

// --- 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, (path, basicFileAttributes) -> true)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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, (path, basicFileAttributes) -> true)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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, (path, basicFileAttributes) -> true)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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, (path, basicFileAttributes) -> true)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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,
        (path, basicFileAttributes) -> basicFileAttributes.isDirectory())) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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,
        (path, basicFileAttributes) -> basicFileAttributes.isRegularFile())) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    18:41                dir
//l----          2022/04/20    18:41                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,
        (path, basicFileAttributes) -> true)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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,
        (path, basicFileAttributes) -> true, FileVisitOption.FOLLOW_LINKS)) {
    stream.forEach(System.out::println);
}

// 結果
// ↓
//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 (final var stream = Files.find(start, Integer.MAX_VALUE, (path, basicFileAttributes) -> true)) {
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// 結果
// ↓
//NoSuchFileException!

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

ファイル属性の値を読み取ります。

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

// Windows固有の属性
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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/14    19:45              4 aaa.txt
//la---          2022/04/14    19:45              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)

指定されたタイプのファイル属性ビューを返します。

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

    // hidden.txtにリードオンリー属性がついたことを確認します。

    // --- 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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/14    20:07              4 aaa.txt
//la---          2022/04/14    20:07              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)

ファイルが置かれているファイル・ストアを表すFileStoreを返します。

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)

ファイルの最終変更時間を返します。

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

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

Files.createFile(path);
final var ret = Files.setLastModifiedTime(path, FileTime.from(
        ZonedDateTime.of(2000, 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
//-------------      ----
//2000/01/01 0:00:00 aaa.txt

// FileTimeはUTCです。
final var fileTime = Files.getLastModifiedTime(path);
System.out.println(fileTime); // 1999-12-31T15:00:00Z

final var zonedDateTime = ZonedDateTime.ofInstant(fileTime.toInstant(), zoneId);
System.out.println(zonedDateTime); // 2000-01-01T00:00+09:00[Asia/Tokyo]
final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // 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

Files.createFile(target);
Files.setLastModifiedTime(target, FileTime.from(
        ZonedDateTime.of(2000, 1, 1, 0, 0, 0, 0, zoneId).toInstant()));

Files.createSymbolicLink(link, target);

// --- PowerShell ---
//PS D:\java-work> ls
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2000/01/01     0:00              0 aaa.txt
//la---          2022/04/14    21:03              0 link.txt -> D:\java-work\aaa.txt

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

final var ret2 = Files.getLastModifiedTime(link, LinkOption.NOFOLLOW_LINKS);
System.out.println(ret2); // 2022-04-14T12:03:42.431078Z

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

ファイルの所有者を返します。

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…

System.out.println(Files.getOwner(link)); // MY-PC\test-user (User)
System.out.println(Files.getOwner(link, LinkOption.NOFOLLOW_LINKS)); // BUILTIN\Administrators (Alias)

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

ファイルのPOSIXファイル・アクセス権を返します。

※以下のコード例は、Linuxで実行しています。

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

// --- Linux Terminal ---
//$ ls -l sample.txt
//-rw-rw-r-- 1 xxxx xxxx 0  9月 24 19:45 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  9月 24 19:55 link.txt -> sample.txt
//-rw-rw-r-- 1 xxxx xxxx  0  9月 24 19:45 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)

ファイルがディレクトリかどうかをテストします。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/14    21:51                dir
//l----          2022/04/14    21:51                link-dir -> D:\java-work\dir
//-a---          2022/04/14    21:51              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)

ファイルが実行可能かどうかをテストします。

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

// 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

※以下のコード例は、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  4月 21 16:30 sample.sh
//-rw-rw-r-- 1 xxxx xxxx    0  4月 21 16:30 sample.txt

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

static boolean isHidden (Path path)

ファイルが隠しファイルとみなされるかどうかを判断します。

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!");
}

// 結果
// ↓
//NoSuchFileException!

static boolean isReadable (Path path)

ファイルが読取り可能かどうかをテストします。

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
// ※non-readable.txtは読み取り権限を拒否にしています。
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)

ファイルが不透明な内容の通常ファイルかどうかをテストします。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/15    17:25                dir
//-a---          2022/04/15    17:25              0 aaa.txt
//la---          2022/04/15    17:25              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)

2つのパスが同じファイルを検出するかどうかを判断します。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/15    17:29              4 aaa1.txt
//-a---          2022/04/15    17:29              4 aaa2.txt
//-a---          2022/04/15    17:29              3 bbb.txt
//la---          2022/04/15    17:29              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!");
}

// 結果
// ↓
//NoSuchFileException!

static boolean isSymbolicLink (Path path)

ファイルがシンボリック・リンクかどうかをテストします。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/15    17:36                dir
//-a---          2022/04/15    17:36              0 aaa.txt
//la---          2022/04/15    17:36              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)

ファイルが書込み可能かどうかをテストします。

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)

ファイル内のすべての行を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)

ファイル内のすべての行をStreamとして読み取ります。

パラメータ cs 以外については、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"))) {
    //stream.toList(); // UncheckedIOException (MalformedInputException)
}
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)) {
    //stream.toList(); // UncheckedIOException (MalformedInputException)
}

static Stream<Path> list (Path dir)

ディレクトリ内のエントリを要素に持つ遅延設定Streamを返します。

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

    // 結果
    // ↓
    //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);

    // 結果
    // ↓
    //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 (final var stream = Files.list(file)) {

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

// 結果
// ↓
//NotDirectoryException!

static long mismatch (Path path, Path path2)

2つのファイルのコンテンツ内で、最初の不一致バイトの位置を検索して返します。不一致がない場合は、-1L。

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

System.out.println(Arrays.toString(Files.readAllBytes(file6))); // [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)

ファイルをターゲット・ファイルに移動するか、そのファイル名を変更します。

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!");
}

// 結果
// ↓
//FileAlreadyExistsException!
// 異なる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
// 異なる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!");
}

// 結果
// ↓
//DirectoryNotEmptyException!

static BufferedReader newBufferedReader (Path path)

ファイルを読込み用に開き、効率的な方法でファイルからテキストを読み込むBufferedReaderを返します。

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)

ファイルを読取り用に開き、そのファイルから効果的な方法でテキストを読み取るために使用できるBufferedReaderを返します。

パラメータ cs 以外については、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!");
}

// 結果
// ↓
//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!");
}

// 結果
// ↓
//MalformedInputException!

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

ファイルを書込み用に開くか作成して、そのファイルに効果的な方法でテキストを書き込むために使用できるBufferedWriterを返します。

パラメータ cs 以外については、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!");
}

// 結果
// ↓
//MalformedInputException!

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

ファイルを書込み用に開くか作成し、効率的な方法でファイルにテキストを書き込むBufferedWriterを返します。

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

// 結果
// ↓
//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)

ファイルを開くか作成し、そのファイルにアクセスするためのシーク可能なバイト・チャネルを返します。

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
//<ファイル・ディレクトリなし>

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)

ファイルを開くか作成し、そのファイルにアクセスするためのシーク可能なバイト・チャネルを返します。

FileAttribute については、createFile(Path path, FileAttribute<?>... attrs) の使用例をご参照ください。

それ以外については newByteChannel(Path path, OpenOption... options) をご参照ください。

static DirectoryStream<Path> newDirectoryStream (Path dir)

ディレクトリを開き、ディレクトリ内のすべてのエントリを反復するためのDirectoryStreamを返します。

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);
    }
}

// 結果
// ↓
//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);
    }
}

// 結果
// ↓
//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 (final var stream = Files.newDirectoryStream(nonExistentPath)) {
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// 結果
// ↓
//NoSuchFileException!

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

ディレクトリを開き、そのディレクトリ内のエントリに対して反復処理を行うDirectoryStreamを返します。

パラメータ glob 以外については、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);
    }
}

// 結果
// ↓
//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);
    }
}

// 結果
// ↓
//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);
    }
}

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

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

ディレクトリを開き、そのディレクトリ内のエントリに対して反復処理を行うDirectoryStreamを返します。

パラメータ filter 以外については、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, (path) -> true)) {
    for (final var path : stream) {
        System.out.println(path);
    }
}

// 結果
// ↓
//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);
    }
}

// 結果
// ↓
//D:\java-work\Book.java
//D:\java-work\Page.java

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

ファイルを開き、そのファイルから読み取る入力ストリームを返します。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/21    20:34              3 aaa.txt
//la---          2022/04/21    20:34              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 (final var inputStream = Files.newInputStream(link, LinkOption.NOFOLLOW_LINKS)) {
} catch (IOException e) {
    System.out.println(e);
}

// 結果
// ↓
//java.io.IOException: File is symbolic link

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

ファイルを開くか作成して、そのファイルにバイトを書き込むために使用できる出力ストリームを返します。

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)

このパスが示すファイルが存在しないかどうかをテストします。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/19    17:04                dir
//-a---          2022/04/19    17:04              0 aaa.txt
//la---          2022/04/19    17:04              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)

ファイルのコンテンツ・タイプを調べます。

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

ファイルからすべてのバイトを読み取ります。

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)

ファイルからすべての行を読み取ります。

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)

ファイルからすべての行を読み取ります。

パラメータ cs 以外については、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!");
}

// 結果
// ↓
//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!");
}

// 結果
// ↓
//MalformedInputException!

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

一括操作としてファイル属性を読み取ります。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/19    17:41              0 aaa.txt
//la---          2022/04/19    17:41              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)

一括操作として一連のファイル属性を読み取ります。

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=2022-04-19T09:14:32.0033232Z, lastModifiedTime=2022-04-19T09:14:32.0033232Z,
// size=0, creationTime=2022-04-19T09:08:20.7198244Z, 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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/19    17:41              0 aaa.txt
//la---          2022/04/19    17:41              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)

ファイルのすべてのコンテンツを文字列に読み込み、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);

// 結果
// ↓
//abcd
//XYZ
//12345

static String readString (Path path, Charset cs)

ファイルのすべての文字を文字列に読み込み、指定されたcharsetを使用してバイトから文字にデコードします。

パラメータ cs 以外については、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!");
}

// 結果
// ↓
//MalformedInputException!

static Path readSymbolicLink (Path link)

シンボリック・リンクのターゲットを読み取ります(オプションの操作)。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/20    17:12              0 link.txt -> D:\java-work\target.txt
//-a---          2022/04/20    17:12              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!");
}

// 結果
// ↓
//NotLinkException!

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

ファイル属性の値を設定します。

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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/20    17:33              0 link.txt -> D:\java-work\target.txt
//-a---          2022/04/20    17:33              0 target.txt

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

// --- PowerShell ---
//PS D:\java-work> ls -Force
//...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la---          2022/04/20    17:33              0 link.txt -> D:\java-work\target.txt
//-a-h-          2022/04/20    17:33              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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//la-h-          2022/04/20    17:34              0 link.txt -> D:\java-work\target.txt
//-a-h-          2022/04/20    17:34              0 target.txt

static Path setLastModifiedTime (Path path, FileTime time)

ファイルの最終変更時間属性を更新します。

このメソッドの使用例は、getLastModifiedTime(Path path, LinkOption... options) にまとめて記載しました。
そちらのAPI使用例をご参照ください。

static Path setOwner (Path path, UserPrincipal owner)

ファイル所有者を更新します。

このメソッドの使用例は、getOwner(Path path, LinkOption... options) にまとめて記載しました。
そちらのAPI使用例をご参照ください。

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

ファイルのPOSIXファイル・アクセス権を設定します。

※以下のコード例は、Linuxで実行しています。

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

// --- Linux Terminal ---
//$ ls -l sample.sh
//-rw-rw-r-- 1 xxxx xxxx 0  9月 24 20:25 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  9月 24 20:25 sample.sh

static long size (Path path)

ファイルのサイズをバイトで返します。

// --- 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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    18:14                dir
//-a---          2022/04/20    18:14              5 aaa.txt
//-a---          2022/04/20    18:14           1000 bbb.txt
//
//    Directory: D:\java-work\dir
//
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/04/20    18:14             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!");
}

// 結果
// ↓
//NoSuchFileException!

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

指定された開始ファイルをルートとするファイル・ツリーを参照することで Pathが遅延移入されるStreamを返します。

パラメータ maxDepth 以外については、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);
}

// 結果
// ↓
//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);
}

// 結果
// ↓
//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);
}

// 結果
// ↓
//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);
}

// 結果
// ↓
//maxDepth : 0
//D:\java-work

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

指定された開始ファイルをルートとするファイル・ツリーを参照することで Pathが遅延移入されるStreamを返します。

// --- 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);
}

// 結果
// ↓
//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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    18:41                dir
//l----          2022/04/20    18:41                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);
}

// 結果
// ↓
//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);
}

// 結果
// ↓
//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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    19:01                dir
//
//    Directory: D:\java-work\dir
//
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//l----          2022/04/20    19:01                link-parent-dir -> D:\java-work\dir
//-a---          2022/04/20    19:01              0 aaa.txt
//-a---          2022/04/20    19:01              0 bbb.txt

// ※link-parent-dirは親の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);
}

// 結果
// ↓
//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);
}

// 結果
// ↓
//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 (final var stream = Files.walk(start)) {
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// 結果
// ↓
//NoSuchFileException!

static Path 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

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

// 結果
// ↓
//-- 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);

// 結果
// ↓
//-- 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);

// 結果
// ↓
//-- 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…

// ※意図的に失敗ケースを発生させるために、dir1ディレクトリは読み取り権限を外しています。

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

// 結果
// ↓
//-- 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)

ファイル・ツリーを参照します。

パラメータ options, maxDepth 以外については、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);

// 結果
// ↓
//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);

// 結果
// ↓
//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);

// 結果
// ↓
//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);

// 結果
// ↓
//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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    18:41                dir
//l----          2022/04/20    18:41                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);

// 結果
// ↓
//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);

// 結果
// ↓
//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                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//d----          2022/04/20    19:01                dir
//
//    Directory: D:\java-work\dir
//
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//l----          2022/04/20    19:01                link-parent-dir -> D:\java-work\dir
//-a---          2022/04/20    19:01              0 aaa.txt
//-a---          2022/04/20    19:01              0 bbb.txt

// ※link-parent-dirは親のdirへのシンボリックリンクです。
// つまりリンクが循環しています。

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

// 結果
// ↓
//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)

バイトをファイルに書き込みます。

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
//<ファイル・ディレクトリなし>

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)

テキスト行をファイルに書き込みます。

パラメータ cs 以外については、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
//<ファイル・ディレクトリなし>

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!");
}

// 結果
// ↓
//MalformedInputException!

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

テキスト行をファイルに書き込みます。

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
//<ファイル・ディレクトリなし>

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)

CharSequenceをファイルに書き込みます。

パラメータ cs 以外については、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
//<ファイル・ディレクトリなし>

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!");
}

// 結果
// ↓
//MalformedInputException!

static Path writeString (Path path, CharSequence csq, OpenOption... options)

CharSequenceをファイルに書き込みます。

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
//<ファイル・ディレクトリなし>

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
//<ファイル・ディレクトリなし>

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]

関連記事

ページの先頭へ