LearnFrenzy
Sign in Take a free test

Java Programming · Topic 24 of 28

File Handling, IO and NIO

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

File Handling, IO and NIO · Study material

Processing big files lazily with Files.lines

Files.lines returns a Stream that reads the file line by line, so even very large files can be filtered and summarised with little memory.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("app", ".log");
        Files.writeString(log, """
            INFO  server started
            WARN  disk 80% full
            INFO  user asha logged in
            ERROR db timeout
            INFO  user ravi logged in
            ERROR payment failed
            """);

        // Files.lines reads LAZILY, one line at a time – good for big files; close it with try-with-resources
        try (Stream<String> lines = Files.lines(log)) {
            Map<String, Long> byLevel = lines.filter(l -> !l.isBlank())
                .collect(Collectors.groupingBy(l -> l.split("\\s+")[0], TreeMap::new, Collectors.counting()));
            System.out.println(byLevel);
        }
        try (Stream<String> lines = Files.lines(log)) {
            System.out.println(lines.filter(l -> l.startsWith("ERROR")).map(l -> l.substring(6)).toList());
        }
        Files.delete(log);
    }
}

Output

{ERROR=2, INFO=3, WARN=1}
[db timeout, payment failed]

PrintWriter and Scanner

PrintWriter brings print, println and printf to any writer; Scanner reads tokens and numbers from a file or any input.

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("report", ".txt");
        try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) {   // printf / println to a file
            pw.printf("%-6s %5s%n", "item", "qty");
            pw.printf("%-6s %5d%n", "pen", 120);
            pw.printf("%-6s %5d%n", "book", 45);
            pw.println("total " + (120 + 45));
        }
        System.out.print(Files.readString(file));

        try (Scanner sc = new Scanner(file)) {                    // Scanner tokenises a file
            sc.nextLine();                                        // skip the header
            int sum = 0;
            while (sc.hasNext()) {
                String word = sc.next();
                if (word.equals("total")) System.out.println("check total = " + sc.nextInt());
                else if (sc.hasNextInt()) sum += sc.nextInt();
            }
            System.out.println("summed " + sum);
        }
        Files.delete(file);
    }
}

Output

item     qty
pen      120
book      45
total 165
check total = 165
summed 165

Legacy java.io.File vs NIO

// Legacy (still common in old code)
File f = new File("data/report.txt");
boolean ok = f.delete();                       // just returns false on failure – no reason given
File[] children = new File("data").listFiles();

// Modern NIO.2
Path p = Path.of("data", "report.txt");
Files.delete(p);                               // throws NoSuchFileException, AccessDeniedException … with details
try (Stream<Path> s = Files.list(Path.of("data"))) { … }

// Converting between them
Path fromFile = f.toPath();
File fromPath = p.toFile();

File handling checklist

  • Use Path and Files for new code.
  • Open every stream, reader and writer in try-with-resources.
  • State the charset (UTF-8) explicitly when converting bytes and text.
  • Buffer readers and writers; stream big files instead of loading them whole.
  • Close Files.lines/list/walk streams.
  • Build paths with resolve, never string concatenation.
  • Handle IOException with a clear message; do not swallow it.
  • Write to a temporary file and move it into place for safe updates.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links