Java / Java File I/O and Serialization

File Handling with Input/Output Streams

This tutorial covers how to use Input and Output Streams in Java for file handling. You'll learn the fundamentals of how data is read and written in Java.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores reading, writing, and manipulating files in Java.

1. Introduction

This tutorial aims to guide you on how to handle file operations in Java using Input and Output Streams. By the end of this tutorial, you will be able to read data from a file and write data to a file using Java's I/O streams.

What you will learn:
- The basics of Input and Output Streams in Java.
- How to read data from a file.
- How to write data to a file.

Prerequisites:
- Basic understanding of Java.
- Familiarity with object-oriented programming concepts.

2. Step-by-Step Guide

Java's I/O operations are based on the concept of streams. A stream is a sequence of data that provides a common I/O model. Java uses two types of streams - byte streams (for binary data) and character streams (for text data).

InputStream and OutputStream:
- InputStream and OutputStream are abstract base classes for reading from and writing to byte streams, respectively.
- Commonly used subclasses of these are FileInputStream and FileOutputStream.

FileInputStream:
- FileInputStream is used to read data from a file.
- It reads data in bytes, so it's suitable for reading binary data.

FileOutputStream:
- FileOutputStream is used to write data to a file.
- It writes data in bytes, so it's suitable for writing binary data.

3. Code Examples

Example 1: Reading a File

import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        try {
            FileInputStream fileInput = new FileInputStream("input.txt");
            int i = 0;
            while((i = fileInput.read()) != -1) {
                System.out.print((char)i);
            }
            fileInput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we're reading from a file named "input.txt". The read() method reads one byte at a time and returns -1 when it reaches the end of the file. We then print each character to the console.

Example 2: Writing to a File

import java.io.*;

public class WriteFile {
    public static void main(String[] args) {
        try {
            FileOutputStream fileOutput = new FileOutputStream("output.txt");
            String data = "Hello, World!";
            byte[] arr = data.getBytes();
            fileOutput.write(arr);
            fileOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we're writing to a file named "output.txt". We convert the string "Hello, World!" to a byte array and then write it to the file using the write() method.

4. Summary

You've learned how to read from and write to files using Java's Input and Output Streams.

Key points covered:
- Understanding of InputStreams and OutputStreams.
- Reading a file with FileInputStream.
- Writing to a file with FileOutputStream.

Next steps for learning:
- Learn about character streams in Java.
- Deep dive into Java's other I/O classes like BufferedReader, BufferedWriter, FileReader, FileWriter, etc.

Additional resources:
- Java Documentation

5. Practice Exercises

Exercise 1: Write a program to read a text file and print the number of lines, words and characters in it.

Exercise 2: Write a program to copy the contents of one file to another.

Exercise 3: Write a program to read a binary file (like an image file) and write it to another file.

Note: Attempt the exercises yourself first. If you're stuck, refer to the code examples provided, the Java documentation, or ask for help online. Happy coding!

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

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Image Converter

Convert between different image formats.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

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