I/O

Overview

InputStream & OutputStream

try (final OutputStream os = new FileOutputStream("a.dat")) {
    os.write(0b01100001); // binary
    os.write('a');        // char
    os.write(97);         // int
} catch (IOException ignored) {}

try (final InputStream fis = new FileInputStream("a.dat")) {
    fis.read(); // 97
    fis.read(); // 97
    fis.read(); // 97
    fis.read(); // -1
    fis.read(); // -1            
}  catch (IOException ignored) {}

Alternative Ways of Reading from Files

Files.readAllBytes(Paths.get("a.dat")); // byte[]

Buffered Streams

Further documentation here.

import java.io.*;
import java.nio.*;
import java.nio.file.*;

class App {
    public static void main(String[] args) throws Exception {
        InputStream inputStream;

        // Without buffer, read 16 bytes at a time
        inputStream = new FileInputStream("big.txt");
        readWholeFile(inputStream, 16);
        inputStream.close();

        // Without buffer, read 2048 bytes at a time
        inputStream = new FileInputStream("big.txt");
        readWholeFile(inputStream, 2048);
        inputStream.close();

        // With buffer, read 16 bytes at a time
        inputStream = new BufferedInputStream(new FileInputStream("big.txt"));
        readWholeFile(inputStream, 16);
        inputStream.close();

        // With buffer, read 2048 bytes at a time
        inputStream = new BufferedInputStream(new FileInputStream("big.txt"));
        readWholeFile(inputStream, 2048);
        inputStream.close();

        // Using Files
        long start = System.currentTimeMillis();
        Files.readAllBytes(Paths.get("big.txt"));
        long end = System.currentTimeMillis();
        System.out.println("Took:" + (end - start) + " ms.");        
    }

    static void readWholeFile(InputStream inputStream, int chunkSize) throws Exception {
        long start, end;
        start = System.currentTimeMillis();
        
        byte[] temp = new byte[chunkSize];
        while (true) {
            int bytesRead = inputStream.read(temp);
            if (bytesRead == -1) {
                break;
            }
        }

        end = System.currentTimeMillis();
        System.out.println("Took:" + (end - start) + " ms.");
    }
}

Output for me reading a 170MB file

Took:15692 ms.
Took:147 ms.
Took:142 ms.
Took:62 ms.
Took:235 ms.

Reader & Writer

try (Writer writer = new OutputStreamWriter(new FileOutputStream("a.txt"), StandardCharsets.UTF_8)) {
    writer.write("Hello World");
    writer.close();
} catch (Exception ignored) {}

try (Reader reader = new InputStreamReader(new FileInputStream("a.txt"), StandardCharsets.UTF_8)) {
    StringBuilder sb = new StringBuilder();
    int read = reader.read();
    while (read != -1) {
        sb.append((char) read);
        read = reader.read();
    }
    System.out.println(sb); // Hello World
} catch (Exception ignored) {}

Line Oriented Reader & Writer

try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("lorem.txt"), "UTF-8"))) {
// This works as well: try (BufferedReader br = new BufferedReader(new FileInputStream("lorem.txt"), "UTF-8")) {
    while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        System.out.println(line);
    }
} catch (Exception ignored) {}

Alternative Ways of Reading Text Files

// Read the whole file into a single string
new String(Files.readAllBytes(Paths.get("a.txt")), StandardCharsets.UTF_8);

// Read a file line by line
Files.readAllLines(Paths.get("a.txt"), StandardCharsets.UTF_8); // List<String>
Files.lines(Paths.get("a.txt"), StandardCharsets.UTF_8);        // Stream<String>

Alternative Ways of Writing Text Files

Files.write(Paths.get("a.txt"), "Hello World".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get("a.txt"), Arrays.asList("Hello World"), StandardCharsets.UTF_8);

References

Path

  • A path is a sequence of directory names, optionally ending with a file name
  • A path that starts with a root component is called an absolute path
    • Otherwise it is called a relative path
Paths.get("/", "Users", "kt", "IdeaProjects"); // absolute path
Paths.get("IdeaProjects"); // relative path

toAbsolutePath and normalize

Paths.get("").toAbsolutePath().normalize(); // /Users/kt

Examples

Downloading a File from the Internet

String imageUrl = "https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg";
InputStream is = new URL(imageUrl).openStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int bytesRead = 0;
while (true) {
    bytesRead = is.read(temp);
    if (bytesRead == -1) {
        break;
    }
    byteArrayOutputStream.write(temp, 0, bytesRead);
}
is.close();
final OutputStream os = Files.newOutputStream(Paths.get("rip.jpg"));
os.write(byteArrayOutputStream.toByteArray());
os.close();