SoFunction
Updated on 2025-03-04

In-depth and easy-to-understand detailed explanation of byte streams and character streams in Java

The input and output (I/O) streams in Java are mainly divided into byte streams and character streams. These two types of streams provide developers with efficient file reading and writing methods, and also solve the problem of character processing in different encoding formats. This article will take you into the deeper understanding of the differences between byte streams and character streams, application scenarios, and how to use them to handle file operations.

1. What is byte stream?

A byte stream is a stream that operates data in units of ** bytes (bytes). It is used to process all types of files, including text files, pictures, videos, etc. The byte stream does not care about the encoding method of the data, and directly transfers the original bytes of the file.

Two top-level abstract classes for byte streams are provided in Java:

  • InputStream: Represents the input byte stream, used to read data.
  • OutputStream: Indicates the output byte stream, used to write data.

Common implementation classes for byte streams:

  • FileInputStreamandFileOutputStream: Used to operate files.
  • BufferedInputStreamandBufferedOutputStream: Byte stream with buffering function improves read and write efficiency.

Example: Copy a file with a byte stream

The following code shows how to use a byte stream to read and write it to another file:

import ;
import ;
import ;
public class ByteStreamExample {
    public static void main(String[] args) {
        String sourceFile = ""; // Source file path        String destinationFile = ""; // Target file path        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destinationFile)) {
            byte[] buffer = new byte[1024]; // Read 1KB of data each time            int bytesRead;
            while ((bytesRead = (buffer)) != -1) {
                (buffer, 0, bytesRead);
            }
            ("File copy successfully!");
        } catch (IOException e) {
            ();
        }
    }
}

Key points:

  • FileInputStreamRead bytes from the file.
  • FileOutputStreamWrites bytes to another file.
  • Use buffers (buffer) Improves efficiency.

2. What is character stream?

A character stream is a stream that operates data in units of ** characters (char)**, designed specifically for processing text files. It automatically converts bytes to characters according to the encoding format or converts characters to bytes.

Two top-level abstract classes for character streams are provided in Java:

  • Reader: Represents the input character stream, used to read characters.
  • Writer: Represents the output character stream, used to write characters.

Common implementation classes for character streams:

  • FileReaderandFileWriter: Used to operate files.
  • BufferedReaderandBufferedWriter: Character stream with buffering function, supports reading by line.

Example: Read and write text files with character streams

The following code shows how to use a character stream to read a text file and write its contents to another file:

import ;
import ;
import ;
public class CharStreamExample {
    public static void main(String[] args) {
        String sourceFile = ""; // Source file path        String destinationFile = ""; // Target file path        try (FileReader fr = new FileReader(sourceFile);
             FileWriter fw = new FileWriter(destinationFile)) {
            char[] buffer = new char[1024]; // Read 1KB of characters each time            int charsRead;
            while ((charsRead = (buffer)) != -1) {
                (buffer, 0, charsRead);
            }
            ("File copy successfully!");
        } catch (IOException e) {
            ();
        }
    }
}

Key points:

  1. FileReaderandFileWriterAutomatically process character encoding.
  2. Use buffers to improve efficiency, and operating by character unit is more suitable for processing text files.

3. The difference between byte stream and character stream

characteristic Byte Stream Character stream
Data Unit Bytes (byte) Characters (char)
Operation object All file types Text files only
Coding processing No encoding process, direct transmission Automatically process encoding
Common Categories InputStreamOutputStream ReaderWriter

Select by:

  • If the file contains non-text data (such as pictures, videos), use byte streams.
  • If the file is plain text, select the character stream first.

4. Advanced usage of character streams

useBufferedReaderRead text by line

BufferedReaderProvidedreadLine()Method, you can read text files by line:

import ;
import ;
import ;
public class BufferedReaderExample {
    public static void main(String[] args) {
        String filePath = "";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = ()) != null) {
                (line);
            }
        } catch (IOException e) {
            ();
        }
    }
}

advantage:

  • Read by line, suitable for processing large files.
  • It has a buffering mechanism internally to improve performance.

useBufferedWriterWrite text

BufferedWriterProvidednewLine()Methods that can quickly write multiple lines of text:

import ;
import ;
import ;
public class BufferedWriterExample {
    public static void main(String[] args) {
        String filePath = "";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
            ("This is the first line of content");
            ();
            ("This is the second line");
            ("Content writing successfully!");
        } catch (IOException e) {
            ();
        }
    }
}

5. Summary

  • Byte StreamIt operates data in bytes and is suitable for all types of files, especially non-text files.
  • Character streamIt operates data in units of characters, is designed for text files, and automatically processes encoding formats.
  • The choice of the two depends on the file type and operation requirements. Byte streams are more general and character streams are more suitable for processing text.

This is the end of this article about the detailed explanation of byte streams and character streams in Java. For more related contents of Java byte streams and character streams, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!