🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java File I/O — Read and Write Files with Scanner and FileWriter

Java Advanced TopicsFile Input and Output🟢 Free Lesson

Java File I/O — Read and Write Files with Scanner and FileWriter

Learning Objectives

  • Read text files line by line with Scanner
  • Write text files with FileWriter
  • Close resources reliably, including with try-with-resources
  • Handle common file errors such as missing files

Overview

Programs often exchange data with files on disk. Configuration files, logs, exports, and reports all require reading text in and writing text out. Java provides many I/O APIs; for beginners, Scanner covers reading and FileWriter covers writing, and both sit on top of streams that move bytes.

A stream is a sequence of data that flows from a source to a destination. Input streams bring data to your program. Output streams carry data away. Character readers and writers add text decoding so you work with strings instead of raw bytes.

Reading a File with Scanner

Scanner can read from files, system input, and strings. When pointed at a File object, it tokenizes text so you can pull whole lines or individual words.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadDemo {
    public static void main(String[] args) {
        try {
            File file = new File("notes.txt");
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

hasNextLine returns true while more lines remain, and getline returns the next line without the line break. If the file does not exist, the constructor throws FileNotFoundException, which is a checked exception you must handle.

For simple whole-file reading, the Files readString method from the java.nio.file package is even shorter and returns the entire content as one String. Scanner remains useful when you want word by word or number by number parsing.

Writing a File with FileWriter

FileWriter creates or truncates a file and writes character data. Pass a second argument of true to append instead of overwrite.

import java.io.FileWriter;
import java.io.IOException;

public class WriteDemo {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("First line");
            writer.write(System.lineSeparator());
            writer.write("Second line");
            writer.close();

            System.out.println("Write complete");
        } catch (IOException e) {
            System.out.println("Write failed: " + e.getMessage());
        }
    }
}

write accepts strings and individual characters. Newline characters must be added explicitly if you want separate lines, because write does not append them for you. Always close the writer so buffered data is flushed to disk.

try-with-resources

Manual close calls are easy to forget, especially when an exception skips them. Java provides try-with-resources, which declares the resource in the try parentheses and closes it automatically at the end of the block.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class SafeRead {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("data.txt"))) {
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("Missing data file");
        }
    }
}

Any class used this way must implement AutoCloseable, which Scanner and FileWriter both do. This pattern is the professional default for files, sockets, and database connections.

Paths in Practice

Relative paths resolve against the working directory of the process, which differs between editors and command line runs. Absolute paths always start at the file system root. When an open fails with not found, verify the path first before suspecting your logic. The Path interface and Paths get factory method offer a modern alternative to the File class and integrate well with the Files utility methods for reading, writing, copying, and deleting.

A Round Trip Example

Reading and writing together enables simple transformations such as uppercasing a file or filtering lines.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class RoundTrip {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(new File("input.txt"));
             FileWriter out = new FileWriter("upper.txt")) {

            while (in.hasNextLine()) {
                out.write(in.nextLine().toUpperCase());
                out.write(System.lineSeparator());
            }
        } catch (FileNotFoundException e) {
            System.out.println("Input missing");
        } catch (IOException e) {
            System.out.println("Output problem");
        }
    }
}

Two resources can share one try header. Both close automatically even if writing throws halfway through.

Key Takeaways

💡

  • Scanner reads files line by line or token by token
  • FileWriter writes text and needs an explicit close or try-with-resources
  • try-with-resources closes AutoCloseable resources automatically
  • File related methods throw checked exceptions you must catch or declare
  • Prefer try-with-resources over manual close for every file operation

Practice Questions

  1. Write a program that counts the number of lines in a text file and prints the count.
  2. How does try-with-resources improve on calling close in a finally block?
  3. Explain the difference between appending with FileWriter and overwriting the default behavior.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement