Wejście i wyjście

Obsługa operacji wejścia i wyjścia za pomocą API Stream oraz NIO


dr inż. Aleksander Smywiński-Pohl

apohllo@o2.pl

http://apohllo.pl/dydaktyka/programowanie-obiektowe

Klasa File

File homedir = new File(System.getProperty("user.home"));

File file = new File(homedir, "plik.txt");

if(file.exists() && file.isFile() && file.canRead()){
    File directory = new File(file, "katalog");
    directory.mkdir();
    file.renameTo(new File(directory, "plik1.txt"))
} else {
    System.out.println("Plik nie istnieje");
}

Metody klasy File

boolean canExecute = file.canExecute();
boolean canRead = file.canRead();
boolean canWrite = file.canWrite();
boolean result;
result = file.setReadOnly();
result = file.setExecutable(true);
result = file.setReadable(true);
String absolutePath = file.getAbsolutePath();
String canonicalPath = file.getCanonicalPath();
String name = file.getName();
String parent = file.getParent();
boolean exists = file.exists();
boolean isAbsolute = file.isAbsolute();
boolean isDirectory = file.isDirectory();
boolean isFile = file.isFile();
boolean renamed = file.renameTo(destination);
boolean deleted = file.delete();
long free = file.getFreeSpace();
long total = file.getTotalSpace();
long usable = file.getUsableSpace();
File[] roots = File.listRoots();

Plik tymczasowy

File temporary = File.createTempFile("prefix", ".txt");
temporary.deleteOnExit();

Strumienie

System.out.println("Przykład strumienia I/O");

Dane binarne

try(InputStream stream = new FileInputStream("/home/apohllo/mozilla.pdf")) {
    byte[] buffer = new byte[4096];
    int length, count = 0;
    while ((length = stream.read(buffer)) > 0) {
        for(int i=0; i < length; i++) {
            if (buffer[i] == 97) count++;
        }
    }
    System.out.println("Liczba występień litery <a>: " + count);
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Dane tekstowe

try (BufferedReader reader = new BufferedReader(
        new FileReader("/home/apohllo/tmp/a.txt"))){

    String line;
    while((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Czytanie z konsoli

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(System.in))) {

    String line;
    while((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Zapis do pliku

File file = new File(System.getProperty("user.home") + File.separator +
    "output.txt");
try (PrintWriter output = new PrintWriter(
        new BufferedWriter(new FileWriter(file)))) {

    output.println("W Szczebrzeszynie chrząszcz brzmi w trzcinie");
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Dekoratory

BufferedReader reader = 
    new BufferedReader(
        new InputStreamReader(
            new GZIPInputStream(
                new FileInputStream(
                    new File("data.txt.gz")))));

Kopiowanie - try z zasobami

try (BufferedReader reader = new BufferedReader(
        new FileReader("/home/apohllo/output.txt"));
     PrintWriter writer = new PrintWriter(
        new BufferedWriter(
            new FileWriter("/home/apohllo/output.cpy")))) {

    String line;

    while((line = reader.readLine()) != null) {
        writer.println(line);
    }
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Wady klasycznego podejścia

  • brak metod do wykonywania popularnych operacji
  • brak jednolitej obsługi nazw plików na różnych platformach
  • brak jednolitego modelu atrybutów plików
  • brak funkcji specyficznych dla okreslonej platformy
  • brak obsługi nieblokujących operacji IO

Nowy system IO - NIO.2

import java.nio.file.*;

Files.copy(Paths.get("/home/apohllo/mozilla.pdf"), 
    Paths.get("/home/apohllo/mozilla.cpy"));
Files.copy(Paths.get("/home/apohllo/mozilla.pdf"), 
    Paths.get("/home/apohllo/mozilla.cpy"),
    StandardCopyOption.REPLACE_EXISTING);
Path source, target;
Attributes attributes;

Files.createFile(target, attributes);
Files.deleteIfExists(target);
Files.copy(source, target);
Files.move(source, target);
long size = Files.size(target);

Files.isDirectory(target);
Files.isSymbolicLink(target);
Charset charset = StandardCharsets.UTF_8;
List<String> lines = Files.readAllLines(target, charset);
byte[] b = Files.readAllBytes(target);
BufferedReader reader = Files.newBufferedReader(target, charset);
BufferedWriter writer = Files.newBufferedWriter(target, charset);
InputStream input = Files.newInputStream(target);
OutputStream output = Files.newOutputStream(target);

Path

import java.nio.charset.*;

Path zipFile = Paths.get("/home/apohllo/file1.zip");
try (FileSystem subSystem =
        FileSystems.newFileSystem(zipFile, null)) {

    Path pathForFile = sybSystem.getPath("/hello.txt");
    List<String> list = new ArrayList<>();
    list.add("Ala ma kota w Szczebrzeszynie");

    File.write(pathForFile, list, Charset.defaultCharset(),
        StandardOpenOption.WRITE, StandardOpenOption.CREATE);
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Asynchroniczne wejście i wyjście

import java.nio.channels.*;

try (AsynchronousFileChannel channel = 
        AsynchronousFileChannel.open(
            Paths.get("/home/apohllo/mozilla.pdf"))) {

    ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 100); // 100 MB
    Future<Integer> result = channel.read(buffer, 0);

    // jakieś działania

    System.out.println("Liczba wczytanych bajtów " + result.get());
} catch (IOException ex) {
    System.out.println("Problem IO: " + ex);
}

Pytania?