io

IO


Überblick

File
OOP-Repräsentation einer Datei
Pfad- und Dateimanipulation
alte java.io Implementierung
Path
OOP-Repräsentation eines Dateipfads
Pfadmanipulation
Files
nur statische Methoden
Dateimanipulation

Path

public interface Path 
        extends Comparable<Path>, Iterable<Path>, Watchable {

    Path getRoot();
    Path getParent();
    Path getFileName();
    int getNameCount();     
    Path getName(int index);
    Path subpath(int beginIndex, int endIndex);
    boolean startsWith(Path other);
    boolean endsWith(Path other);
    Path resolve(Path other);
    Path relativize(Path other);
    URI toUri();
    default File toFile() { ... }


Path path  = Path.of("C:/data/images/2020/img.jpg");
Path root = path.getRoot();         => C:\
Path parent = path.getParent();     => C:\data\images\2020
Path fileName = path.getFileName(); => img.jpg

List parts = new ArrayList<>();
for (int i = 0; i < path.getNameCount(); i++)
    parts.add(path.getName(i));     => [data, images, 2020, img.jpg]

Path subPath = path.subpath(2, 4);          => 2020\img.jpg
Path stuff = Path.of("other/stuff");
Path resolved = stuff.resolve(subPath);     => other\stuff\2020\img.jpg
Path music = Path.of("other/music");    
Path relativized = stuff.relativize(music); => ..\music

Files


Input-/OutputStream

try (DataOutputStream output = new DataOutputStream(
        Files.newOutputStream(path))) {
    output.writeByte(2);
}
try (DataOutputStream output = new DataOutputStream(
        Files.newOutputStream(path, StandardOpenOption.APPEND))) {
    output.writeByte(3);
}

try (DataInputStream input = new DataInputStream(
        Files.newInputStream(path))) {
    System.out.println(input.readByte());   => 2
    System.out.println(input.readByte());   => 3
}

byte[] all = Files.readAllBytes(path);  => [2, 3] ⚠️ RAM
byte[] toWrite = {5, 7, 9};
Files.write(path, toWrite, StandardOpenOption.APPEND);
all = Files.readAllBytes(path);         => [2, 3, 5, 7, 9]

Reader/Writer

try (PrintWriter writer = new PrintWriter(
        Files.newBufferedWriter(path, StandardOpenOption.CREATE))) {
    writer.println("line 1");
    writer.println("line 2");
}

try (BufferedReader reader = Files.newBufferedReader(path)) {
    String line = reader.readLine();    => line 1
}
String line = "line 3" + System.lineSeparator();
Files.writeString(path, line, StandardOpenOption.APPEND);
List<String> lines = List.of("line 4", "line 5");
Files.write(path, lines, StandardOpenOption.APPEND);

String content = Files.readString(path);    => line 1%nline 2%n... ⚠️ RAM

List lines = Files.readAllLines(path);    => [line 1, ...] ⚠️ RAM
try (Stream<String> lines = Files.lines(path)) { ... }   ✔️ RAM

Checks

public static boolean exists(Path path, LinkOption... options)
public static boolean notExists(Path path, LinkOption... options)
public static boolean isDirectory(Path path, LinkOption... options)
public static boolean isRegularFile(Path path, LinkOption... options)
public static boolean isSymbolicLink(Path path)
public static boolean isSameFile(Path path, Path path2)
public static boolean isReadable(Path path)
public static boolean isWritable(Path path)
public static boolean isExecutable(Path path)
public static boolean isHidden(Path path)

File/Directory Handling

Path path = Path.of("C:/data");
Path images = path.resolve(Path.of("images"));
Files.createDirectory(images);
Path images2020 = path.resolve(Path.of("images/2020/2/"));
Files.createDirectory(images2020);
Exception in thread "main" java.nio.file.NoSuchFileException: 
        C:\data\images\2020\2
Path images2020 = path.resolve(Path.of("images/2020/2/"));
Files.createDirectories(images2020);

erzeugt alle notwendigen Directories

public static void delete(Path path)
public static boolean deleteIfExists(Path path)
public static Path copy(Path source, Path target, CopyOption... options)
public static Path move(Path source, Path target, CopyOption... options)

list etc.

try(Stream<Path> paths = Files.list(Path.of("C:/Windows"))) {
    List<Path> all = paths.collect(Collectors.toList());
}
[alle Folder, alle Files]

mit Glob

List<Path> inis = new ArrayList<>();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(
        Path.of("C:/Windows"), "*.ini")) {
    for (Path entry : paths)
        inis.add(entry);
}
[C:\Windows\system.ini, C:\Windows\win.ini]

beide bleiben im übergebenen Path


Rekursiv

PathMatcher matcher = FileSystems.getDefault()
        .getPathMatcher("glob:**IntelliJ**runner*.exe");
root\folder\folder\...\%IntelliJ%\folder\folder\...\%runner%.exe
try (Stream<Path> paths = Files.find(
        Path.of("C:/Program Files/JetBrains"),
        3,
        (p, a) -> matcher.matches(p))) {
    List<Path> runners = paths.collect(Collectors.toList());
}
[runnerw.exe, runnerw64.exe]