Java Cheatsheet

File I/O

Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Path Basics

Path p = Path.of("/home/user/file.txt");          // Java 11+
Path p2 = Paths.get("/home/user/file.txt");       // Java 7+
Path p3 = Paths.get("/home", "user", "file.txt"); // join segments

p.toString()          // "/home/user/file.txt"
p.getFileName()       // Path "file.txt"
p.getParent()         // Path "/home/user"
p.getRoot()           // Path "/" (or null for relative)
p.getNameCount()      // 3 (number of name elements)
p.getName(0)          // Path "home"
p.subpath(1, 3)       // Path "user/file.txt"
p.isAbsolute()        // true

// Building paths
Path dir  = Path.of("/tmp");
Path file = dir.resolve("data.txt");           // /tmp/data.txt
Path up   = file.resolveSibling("other.txt");  // /tmp/other.txt
Path rel  = Path.of("/tmp").relativize(file);  // data.txt
Path norm = Path.of("/a/../b").normalize();    // /b

// Current directory
Path cwd = Path.of("").toAbsolutePath();
Path cwd2 = Path.of(System.getProperty("user.dir"));

Reading Files

// Read all bytes
byte[] bytes = Files.readAllBytes(Path.of("file.bin"));

// Read as string (UTF-8)
String content = Files.readString(Path.of("file.txt"));              // Java 11+
String content2 = Files.readString(Path.of("file.txt"), StandardCharsets.ISO_8859_1);

// Read all lines as List<String>
List<String> lines = Files.readAllLines(Path.of("file.txt"));

// Read as Stream<String> (lazy — good for large files)
try (Stream<String> stream = Files.lines(Path.of("file.txt"))) {
    stream.filter(l -> !l.isBlank())
          .forEach(System.out::println);
}

// Buffered reader
try (BufferedReader br = Files.newBufferedReader(Path.of("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

Writing Files

// Write string (creates or overwrites)
Files.writeString(Path.of("file.txt"), "Hello, World!");                  // Java 11+
Files.writeString(Path.of("file.txt"), "content", StandardOpenOption.APPEND);

// Write bytes
Files.write(Path.of("file.bin"), new byte[]{1,2,3});

// Write lines
List<String> lines = List.of("line1","line2","line3");
Files.write(Path.of("file.txt"), lines);
Files.write(Path.of("file.txt"), lines, StandardCharsets.UTF_8,
    StandardOpenOption.APPEND);

// Buffered writer
try (BufferedWriter bw = Files.newBufferedWriter(Path.of("file.txt"))) {
    bw.write("Hello");
    bw.newLine();
    bw.write("World");
}

// PrintWriter (for formatted output)
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(Path.of("out.txt")))) {
    pw.printf("Name: %s%n", "Alice");
    pw.println("done");
}

StandardOpenOption Values

OptionEffect
WRITEOpen for writing (default)
READOpen for reading
APPENDAppend to end
TRUNCATE_EXISTINGClear file before writing
CREATECreate if not exists
CREATE_NEWCreate; fail if exists
DELETE_ON_CLOSEDelete when closed
SYNCSync content+metadata to device on every write
DSYNCSync data (not metadata) on every write

Checking File / Directory Existence

Path p = Path.of("file.txt");

Files.exists(p)                        // true/false (follows symlinks)
Files.notExists(p)                     // true if definitely not exists
Files.isReadable(p)
Files.isWritable(p)
Files.isExecutable(p)
Files.isRegularFile(p)
Files.isDirectory(p)
Files.isSymbolicLink(p)
Files.isHidden(p)
Files.size(p)                          // bytes
Files.getLastModifiedTime(p)           // FileTime

Creating, Copying, Moving, Deleting

// Create
Files.createFile(Path.of("newfile.txt"));                 // fails if exists
Files.createDirectory(Path.of("newdir"));                 // parent must exist
Files.createDirectories(Path.of("a/b/c"));               // creates all parents

// Temporary
Path tmp = Files.createTempFile("prefix", ".tmp");
Path tmpDir = Files.createTempDirectory("work");

// Copy
Files.copy(src, dst);                                     // fails if dst exists
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES);
Files.copy(inputStream, dst);                             // from InputStream
Files.copy(src, outputStream);                            // to OutputStream

// Move / Rename
Files.move(src, dst);
Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);    // atomic on same filesystem

// Delete
Files.delete(p);                    // throws NoSuchFileException if not found
Files.deleteIfExists(p);            // returns false if not found

Directory Listing and Walking

// List immediate children (not recursive)
try (Stream<Path> entries = Files.list(Path.of("/tmp"))) {
    entries.filter(Files::isRegularFile)
           .forEach(System.out::println);
}

// Walk tree recursively
try (Stream<Path> tree = Files.walk(Path.of("/project"))) {
    tree.filter(p -> p.toString().endsWith(".java"))
        .forEach(System.out::println);
}

// Walk with depth limit
try (Stream<Path> tree = Files.walk(Path.of("."), 2)) { ... }

// Find files matching a predicate
try (Stream<Path> found = Files.find(Path.of("."), Integer.MAX_VALUE,
        (p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".md"))) {
    found.forEach(System.out::println);
}

// DirectoryStream (classic, for simple glob patterns)
try (DirectoryStream<Path> ds = Files.newDirectoryStream(Path.of("."), "*.java")) {
    for (Path file : ds) System.out.println(file);
}

File Attributes

// Basic attributes
BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class);
attrs.creationTime()
attrs.lastModifiedTime()
attrs.lastAccessTime()
attrs.size()
attrs.isRegularFile()
attrs.isDirectory()
attrs.isSymbolicLink()

// POSIX attributes (Unix/Linux/Mac)
PosixFileAttributes posix = Files.readAttributes(p, PosixFileAttributes.class);
posix.owner()
posix.group()
posix.permissions()   // Set<PosixFilePermission>

// Set permissions
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-xr-x");
Files.setPosixFilePermissions(p, perms);

Channels and ByteBuffers (NIO)

import java.nio.*;
import java.nio.channels.*;

// FileChannel for direct byte access
try (FileChannel fc = FileChannel.open(Path.of("file.bin"),
        StandardOpenOption.READ)) {
    ByteBuffer buf = ByteBuffer.allocate(1024);
    while (fc.read(buf) > 0) {
        buf.flip();                // switch from write to read mode
        while (buf.hasRemaining()) {
            byte b = buf.get();
        }
        buf.clear();
    }
}

// Memory-mapped file (efficient for large files)
try (FileChannel fc = FileChannel.open(Path.of("large.bin"),
        StandardOpenOption.READ)) {
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    byte first = mbb.get(0);
}

Character Streams (java.io)

// Reading with FileReader / BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    br.lines().forEach(System.out::println);
}

// Writing with FileWriter / BufferedWriter / PrintWriter
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("out.txt")))) {
    pw.println("Hello");
    pw.printf("Pi = %.4f%n", Math.PI);
}

// Append to existing file
try (FileWriter fw = new FileWriter("log.txt", true)) {  // true = append
    fw.write("new entry\n");
}

Byte Streams (java.io)

// Reading bytes
try (FileInputStream fis = new FileInputStream("file.bin");
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    int b;
    while ((b = bis.read()) != -1) {
        // process byte b
    }
}

// Writing bytes
try (FileOutputStream fos = new FileOutputStream("out.bin");
     BufferedOutputStream bos = new BufferedOutputStream(fos)) {
    bos.write(new byte[]{0x48,0x65,0x6C,0x6C,0x6F});
}

// Copy file using streams
try (InputStream in  = new BufferedInputStream(new FileInputStream("src.bin"));
     OutputStream out = new BufferedOutputStream(new FileOutputStream("dst.bin"))) {
    byte[] buf = new byte[8192];
    int n;
    while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
}

Serialization

// Serialize (write object to file)
// Class must implement java.io.Serializable
public class Config implements Serializable {
    private static final long serialVersionUID = 1L;  // version stamp
    private String host;
    private int port;
    transient String password;  // transient — NOT serialized
}

// Write
try (ObjectOutputStream oos = new ObjectOutputStream(
        new BufferedOutputStream(new FileOutputStream("config.ser")))) {
    oos.writeObject(new Config("localhost", 8080));
}

// Read
try (ObjectInputStream ois = new ObjectInputStream(
        new BufferedInputStream(new FileInputStream("config.ser")))) {
    Config cfg = (Config) ois.readObject();   // ClassNotFoundException risk
}

Prefer JSON/Protobuf serialization over Java object serialization for new code. Java serialization has security and compatibility issues.

WatchService — File System Events

WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Path.of("/tmp/watch");
dir.register(watcher,
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_DELETE,
    StandardWatchEventKinds.ENTRY_MODIFY);

while (true) {
    WatchKey key = watcher.take();    // blocks until event
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();
        Path changed = (Path) event.context();
        System.out.println(kind + ": " + changed);
    }
    boolean valid = key.reset();
    if (!valid) break;
}

Charset Encoding

import java.nio.charset.*;

// Writing with explicit charset
Files.writeString(p, content, StandardCharsets.UTF_8);
Files.writeString(p, content, StandardCharsets.ISO_8859_1);

// Reader/Writer with charset
new InputStreamReader(new FileInputStream("f.txt"), StandardCharsets.UTF_8)
new OutputStreamWriter(new FileOutputStream("f.txt"), StandardCharsets.UTF_8)

// Common charsets
StandardCharsets.UTF_8
StandardCharsets.UTF_16
StandardCharsets.ISO_8859_1
StandardCharsets.US_ASCII
Charset.forName("Windows-1252")     // by name
Charset.defaultCharset()            // JVM default (avoid — use explicit)