Java / Java File I/O and Serialization

Reading and Writing Files in Java

This tutorial will walk you through the basics of reading and writing files in Java. This is a fundamental skill in Java programming that will be useful in a variety of situations.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores reading, writing, and manipulating files in Java.

1. Introduction

In this tutorial, we will focus on how to read and write files in Java. This is an important aspect of Java programming as it allows you to interact with data stored in files. By the end of this tutorial, you will be able to read data from a file, write data to a file, and handle exceptions during these operations.

Prerequisites:
- Basic knowledge of Java programming.
- Familiarity with Java's exception handling.

2. Step-by-Step Guide

Java provides several classes to perform file operations. These classes can be found in the java.io package. The two main classes we will learn about in this tutorial are FileReader and FileWriter.

FileReader Class:
This class is used to read data from a file. It uses the default character encoding to read data.

FileWriter Class:
This class is used to write data to a file. Similar to FileReader, it uses the default character encoding to write data.

3. Code Examples

Example 1: Reading a File

import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("test.txt"); // Specify the file name
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character); // Cast to char and display it
            }
            reader.close(); // Always close the reader
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we're opening a file called test.txt and reading from it. We keep reading characters until there are none left (reader.read() returns -1 when the end of the file is reached). The read characters are then displayed to the console.

Example 2: Writing to a File

import java.io.*;

public class WriteFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt"); // Specify the file name
            writer.write("Hello, World!"); // Write to the file
            writer.close(); // Always close the writer
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we're creating a file called output.txt and writing "Hello, World!" to it. It's crucial to close the FileWriter after we're done to prevent any resource leaks.

4. Summary

In this tutorial, we have learnt how to read from and write to files in Java using FileReader and FileWriter classes. These are fundamental skills that you will find useful in many programming scenarios.

5. Practice Exercises

Exercise 1: Write a Java program to read a text file and print each line to the console.

Exercise 2: Write a Java program to write the numbers 1 to 10 into a text file, each on a new line.

Exercise 3: Write a Java program to copy the content of one text file to another.

Remember to try these exercises on your own before looking at the solutions. With practice, you will become more comfortable with these concepts.

6. Further Resources

For more detailed information on file handling in Java, check out the official Java documentation: Java IO.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Watermark Generator

Add watermarks to images easily.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help