AlgoGalaxy

AlgoGalaxy

University
CodeRush
Jobs
Tools
Insights
Explore
Personalize
KotlinGoPHPRustGraphsArraysBit ManipulationDynamic ProgrammingGreedyHeapLinked ListStackStringsTreesTrieBacktrackingBinary SearchBSTComplexity AnalysisData Structures & Algorithms

Java: Java | I/O - Paths, Files, and Resources

Let us study Java | I/O like we would in a careful Java review. We will read a small executable example, predict its output, then change one boundary only after we can explain the original contract.

Paths, Files, and Resources is not a checklist to memorize. It is the part of Java design where clear names, deliberate ownership, and observable failures save us from debugging a vague symptom later.

What We Will Practise Together

We are practising more than syntax. For every example, state what Java guarantees, what the caller can observe, and what should happen when the input is missing, invalid, or late.

  • Keep the contract smaller than the explanation around it.
  • Use the type system and resource boundaries to make invalid states difficult.
  • Test the normal path and the closest failure path together.
  • Do not log secrets or pretend a failure is a success.

Example 1: Build a Path instead of concatenating strings

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.Path;

public class Main {
  public static void main(String[] args) {
    Path report = Path.of("reports", "today.txt");
    System.out.println(report.getFileName());
  }
}

Expected Result

today.txt

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 2: Write and read a small UTF-8 file

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    Path file = Files.createTempFile("lesson", ".txt");
    Files.writeString(file, "ready");
    System.out.println(Files.readString(file));
    Files.deleteIfExists(file);
  }
}

Expected Result

ready

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 3: Check existence before assuming a file

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) {
    System.out.println(Files.exists(Path.of("missing.txt")));
  }
}

Expected Result

false

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 4: Read lines lazily

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    Path file = Files.createTempFile("lesson", ".txt");
    Files.writeString(file, "one\ntwo");
    try (var lines = Files.lines(file)) { System.out.println(lines.count()); }
    Files.deleteIfExists(file);
  }
}

Expected Result

2

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 5: Use buffering for character streams

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.io.BufferedReader;
import java.io.StringReader;

public class Main {
  public static void main(String[] args) throws Exception {
    try (var reader = new BufferedReader(new StringReader("line"))) {
      System.out.println(reader.readLine());
    }
  }
}

Expected Result

line

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 6: Keep encoding explicit

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.charset.StandardCharsets;

public class Main {
  public static void main(String[] args) {
    byte[] bytes = "A".getBytes(StandardCharsets.UTF_8);
    System.out.println(bytes.length);
  }
}

Expected Result

1

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 7: Create directories safely

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    Path directory = Files.createTempDirectory("lesson");
    System.out.println(Files.isDirectory(directory));
    Files.deleteIfExists(directory);
  }
}

Expected Result

true

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 8: Make a missing file a named outcome

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

import java.nio.file.NoSuchFileException;

public class Main {
  public static void main(String[] args) {
    try { throw new NoSuchFileException("notes.txt"); }
    catch (NoSuchFileException error) { System.out.println("file is missing"); }
  }
}

Expected Result

file is missing

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 9: Avoid loading unbounded data by default

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

public class Main {
  static boolean isSafeSize(long bytes) { return bytes <= 1_000_000; }

  public static void main(String[] args) { System.out.println(isSafeSize(1200)); }
}

Expected Result

true

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Example 10: Review resource ownership

Let us trace this Java decision together. First say what the input represents. Then identify the exact rule Java applies. Finally compare the expected output with what you predicted before editing the snippet.

A strong implementation keeps the nearest failure, type boundary, or resource owner visible. That makes this example safe to reuse instead of merely impressive in isolation.

Java

public class Main {
  public static void main(String[] args) {
    System.out.println("open -> use -> close");
  }
}

Expected Result

open -> use -> close

Teacher check: alter one input or boundary, predict the new output, and explain the behavior in Java terms before you move on.

Teacher Review

Before we close paths, files, and resources, narrate one example without looking at the code. If you can state the input, rule, output, and boundary in order, you have a reusable Java decision rather than an isolated answer.

Now carry one example into a small project. Keep its expected result beside the code while you change it. That is how we build reliable Java judgment one visible contract at a time.

Practice Before You Move On

Choose one snippet and make a small deliberate change. Write the predicted result first, then run it. If the result surprises you, reduce the example until every step is explainable.

logo of AlgoGalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

AlgoGalaxy University

University HomeTechnology LearningCoding ProblemsLearning ProgressCareer OpportunitiesTechnology InsightsUtilNexa ToolsAlgoGalaxy HomeContact Support

AlgoGalaxy CodeRush

CodeRush HomeProblem SetsProgress TrackerLearn TechnologyTechnology JobsEngineering InsightsDeveloper UtilitiesAlgoGalaxy HomePrivacy Policy
Privacy Policy

 • 

Terms of Service

Copyright © AlgoGalaxy 2026