Table of Contents
1. InputStreamReader class
2. InputStreamReader construction method
3. InputStreamReaderAPI
4. The relationship between the InputStreamReader class and the FileReader class
Home Java javaTutorial How to construct the InputStreamReader stream in JAVA

How to construct the InputStreamReader stream in JAVA

May 17, 2023 pm 10:43 PM
java inputstreamreader

1. InputStreamReader class

API documentation description: The InputStreamReader class is a bridge from a byte stream to a character stream: it reads bytes using the specified character set and decodes them into characters. The character set it uses can be set by specifying a name, explicitly specifying it, or accepting the platform default character set. Each call to an InputStreamReader's read() method may result in one or more bytes being read from the underlying byte input stream. To achieve efficient conversion of bytes to characters, more bytes can be extracted from the underlying stream than required to satisfy the current read operation. In order to operate more efficiently, please consider using InputStreamReader as the basis and packaging it in BufferedReader

It inherits the Reader class

public class InputStreamReader extends Reader {}
Copy after login

1) How to understand the bridge from byte stream to character stream ?

1. The unit of computer storage is bytes. For example, although there are characters such as Chinese characters in the txt text, to the computer, they exist in the form of bytes

2. Byte stream reading is single-byte reading, but different character sets require different numbers to decode into characters, so byte stream reading will report an error

Read from the byte stream for caching Bytes and decoded into characters through the character set are returned, which needs to be implemented using a stream. This is the form of the character stream

4. The InputStreamReader stream plays this role, realizing the conversion from a byte stream to a character stream.

2) How do you understand using the specified character set to read bytes and decode them into characters?

Bytes are essentially 8 binary bits, and different character sets decode the same byte to produce different character results. Therefore, you must specify the appropriate character set when reading characters, otherwise The read content will produce garbled characters

3) The character set it uses can be specified by name, or it can be specified explicitly, or it can accept the default character set of the platform. How to understand?

means that the InputStreamReader class has multiple methods or multiple constructors to set the character set

4) Each time the read() method of an InputStreamReader is called, it may cause How to understand reading one or more bytes from the underlying byte input stream?

read() method will try to read 2 characters from the underlying byte stream into the character buffer. Note that this is a try. If it encounters the last character of the file, it can only read 1 character is obtained, so the number of bytes read by each read() method is variable

5) In order to achieve effective conversion of bytes to characters, the ratio can be extracted from the basic stream To meet more bytes required for the current read operation, please consider wrapping the InputStreamReader in BufferedReader

I don’t understand this yet. You need to understand the BufferedReader class and compare the reading efficiency to get the answer

2. InputStreamReader construction method

1) Use the default character set to construct the InputStreamReader stream: the essence is to initialize a variable in its instance domain, and no settings about the character set are seen

 public InputStreamReader(InputStream in) {
        super(in);
        try {
            sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
        } catch (UnsupportedEncodingException e) {
           
            throw new Error(e);
        }
    }
Copy after login

2) Use the specified character set name to construct the InputStreamReader stream: the essence is to initialize a variable in its instance domain. You can find that the character set is the third parameter of the initialization method

 public InputStreamReader(InputStream in, String charsetName)
        throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }
Copy after login

3) sd variable: It is essentially an object of the StreamDecoder class. The construction method of InputStreamReader is to initialize this object.

private final StreamDecoder sd;
Copy after login

3. InputStreamReaderAPI

1. We can find that all APIs of the InputStreamReaderAPI class use sd variable, so it can be seen that the essence of the method of the InputStreamReader class is to call the StreamDecoder class method

2. Therefore, we need to understand the StreamDecoder class in order to understand how the methods of the InputStreamReader class play a substantial role

    /**
     * 获取设置的字符集
     */
    public String getEncoding() {
        return sd.getEncoding();
    }
 
    /**
     * 读取流并返回一个字符,遇到文件末尾返回-1
     */
    public int read() throws IOException {
        return sd.read();
    }
 
    /**
     * 读取字符到字符数组的部分中,遇到文件末尾返回-1
     */
    public int read(char cbuf[], int offset, int length) throws IOException {
        return sd.read(cbuf, offset, length);
    }
 
    /**
     * 检测流是否准备好呗读取
     */
    public boolean ready() throws IOException {
        return sd.ready();
    }
 
    /**
    * 关闭流并释放资源
    */
    public void close() throws IOException {
        sd.close();
    }
Copy after login

4. The relationship between the InputStreamReader class and the FileReader class

1. The FileReader class is just a simple derivative of InputStreamReader and does not extend any functions

2. The essence of the data read by the FileReader class is that of the InputStreamReader class. Reading, and the data read by InputStreamReader is actually read by the StreamDecoder class

3. Therefore, when using the character input stream, the StreamDecoder class is actually at play

The above is the detailed content of How to construct the InputStreamReader stream in JAVA. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles