Cheat SheetsJava A–ZI/O & Networking

I/O & Networking — Cheat Sheet

Java A–Z · 6 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
I/O & Networking
Java A–Z6 topicsQuick revision reference
1

File I/O

  • Use Files.readString / writeString for small files; Files.lines() for large ones (lazy).
  • Always specify charset (StandardCharsets.UTF_8) — never rely on platform default.
  • Wrap streams in try-with-resources to ensure the file handle is always closed.
  • Files.walk() and Files.find() enumerate directory trees lazily.
  • Files.createDirectories() creates the full path; createDirectory() requires parent to exist.
FilesAPI.java
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

Path path = Path.of("data/users.txt");

// Read entire file
String content = Files.readString(path, StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(path);

// Write entire file (overwrites)
Files.writeString(path, "Hello, World!\n");
Files.write(path, lines); // write List<String>

// Append
Files.writeString(path, "new line\n",
    StandardOpenOption.APPEND, StandardOpenOption.CREATE);

// Large file — lazy stream
try (var stream = Files.lines(path)) {
    long count = stream
        .filter(l -> l.startsWith("ERROR"))
        .count();
}
2

NIO.2 — Non-Blocking I/O

  • Path is immutable and replaces java.io.File for NIO.2 operations.
  • resolve() appends a path; relativize() computes relative path; normalize() cleans . and ..
  • WatchService monitors directories for ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE events.
  • AsynchronousFileChannel reads/writes without blocking, using callbacks or Future.
  • Always call key.reset() in the WatchService loop to continue receiving events.
PathAPI.java
import java.nio.file.*;

Path base    = Path.of("/home/user/projects");
Path subPath = base.resolve("myapp/src/Main.java");
// /home/user/projects/myapp/src/Main.java

Path relative = base.relativize(subPath);
// myapp/src/Main.java

Path norm = Path.of("/home/user/../user/./projects").normalize();
// /home/user/projects

// Path components
System.out.println(subPath.getFileName());  // Main.java
System.out.println(subPath.getParent());    // .../src
System.out.println(subPath.getRoot());      // /
System.out.println(subPath.getNameCount()); // 5

// Check file attributes
System.out.println(Files.isReadable(subPath));
System.out.println(Files.size(subPath));
System.out.println(Files.getLastModifiedTime(subPath));
3

Serialization

  • Implement Serializable to enable serialization; add serialVersionUID for version stability.
  • transient fields are excluded; static fields are never serialized.
  • Override writeObject/readObject for custom serialization logic.
  • readResolve() controls what instance is returned after deserialization (used by Singletons).
  • Prefer JSON/Protobuf over Java serialization for new code — it is a security risk without ObjectInputFilter.
Serialization.java
import java.io.*;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private transient String password; // excluded

    public User(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
    // getters...
}

// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("user.ser"))) {
    oos.writeObject(new User("Alice", 30, "secret"));
}

// Deserialize
try (ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("user.ser"))) {
    User user = (User) ois.readObject();
    System.out.println(user.getName()); // Alice
    System.out.println(user.getPassword()); // null (transient)
}
4

HTTP Client (Java 11+)

  • HttpClient is reusable and thread-safe — create once and share.
  • send() blocks the calling thread; sendAsync() returns a CompletableFuture.
  • BodyHandlers: ofString(), ofBytes(), ofFile(), ofInputStream() parse response body.
  • BodyPublishers: ofString(), ofByteArray(), ofFile(), noBody() provide request body.
  • HttpClient supports HTTP/2 multiplexing and automatic redirect following.
SyncHttp.java
import java.net.http.*;
import java.net.URI;

HttpClient client = HttpClient.newBuilder()
    .version(HttpClient.Version.HTTP_2)
    .connectTimeout(Duration.ofSeconds(10))
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/users"))
    .header("Accept", "application/json")
    .header("Authorization", "Bearer " + token)
    .GET()
    .timeout(Duration.ofSeconds(30))
    .build();

HttpResponse<String> response = client.send(
    request, HttpResponse.BodyHandlers.ofString());

System.out.println("Status: " + response.statusCode());
System.out.println("Body:   " + response.body());
5

Socket Programming

  • ServerSocket.accept() blocks until a client connects; handle each client in a thread.
  • Virtual threads (Java 21) make thread-per-connection scalable — prefer over NIO selectors for new code.
  • UDP uses DatagramSocket/DatagramPacket; TCP uses Socket/ServerSocket.
  • NIO SocketChannel + Selector enables a single thread to multiplex many connections.
  • Always close sockets with try-with-resources to release OS file descriptors.
TcpEcho.java
// --- Server ---
try (ServerSocket server = new ServerSocket(8080)) {
    System.out.println("Listening on port 8080...");
    while (true) {
        Socket client = server.accept(); // blocks
        // Handle each client in a thread
        Thread.ofVirtual().start(() -> handleClient(client));
    }
}

void handleClient(Socket socket) {
    try (socket;
         var in  = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         var out = new PrintWriter(socket.getOutputStream(), true)) {
        String line;
        while ((line = in.readLine()) != null) {
            out.println("Echo: " + line);
        }
    } catch (IOException e) { /* log */ }
}

// --- Client ---
try (Socket socket = new Socket("localhost", 8080);
     var out = new PrintWriter(socket.getOutputStream(), true);
     var in  = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
    out.println("Hello, Server!");
    System.out.println(in.readLine()); // Echo: Hello, Server!
}
6

JDBC — Database Connectivity

  • Always use PreparedStatement — never concatenate user input into SQL strings.
  • Use try-with-resources for Connection, PreparedStatement, and ResultSet.
  • Disable auto-commit for multi-step transactions; call rollback() on exception.
  • Use connection pooling (HikariCP) in production — creating a connection per request is very slow.
  • JDBC URLs follow the pattern: jdbc:<driver>://<host>:<port>/<database>.
JdbcQuery.java
import java.sql.*;

String url  = "jdbc:postgresql://localhost:5432/mydb";
String user = "admin";
String pass = "secret";

try (Connection conn = DriverManager.getConnection(url, user, pass);
     PreparedStatement ps = conn.prepareStatement(
         "SELECT id, name, email FROM users WHERE active = ?")) {

    ps.setBoolean(1, true);

    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            int    id    = rs.getInt("id");
            String name  = rs.getString("name");
            String email = rs.getString("email");
            System.out.printf("%d: %s <%s>%n", id, name, email);
        }
    }
}
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/java