This article is shared from the Huawei Cloud Community " In-depth Understanding of the Reader Class in Java: Step-by-Step Analysis " by Bugger.
Preface
During Java development, we often need to read data from files, and reading data requires a suitable class for processing. Java's IO package provides many classes for reading and writing data, among which Reader is one of them. This article will introduce Reader in Java in detail and analyze its advantages, disadvantages and application scenarios.
Summary
Reader
This article will introduce classes in Java in detail from the following aspects :
- Overview of the Reader class
- Analysis of Reader class code
- Application scenario cases of Reader class
- Analysis of advantages and disadvantages of Reader class
- Reader class method introduction and source code analysis
- Test cases for Reader class
- Full text summary and summary
- Attached source code
- suggestion
This article provides a detailed explanation of Reader in Java, aiming to help developers better understand how to use Reader.
Reader class
Overview
Reader class is an abstract class in Java for reading character streams. It is the superclass of all character input streams and provides basic functions for reading character input streams. The Reader class is mainly implemented by three classes, namely InputStreamReader, FileReader and CharArrayReader.
Source code analysis
Reader
Class is an abstract class, and its source code is defined as follows:
public abstract class Reader implements Readable, Closeable { ... }
Among them, Reader implements two interfaces: Readable
and Closeable
. Readable
There is only one method defined in the interface:
public interface Readable { int read(CharBuffer cb) throws IOException; }
There Closeable
is only one method defined in the interface:
public interface Closeable extends AutoCloseable { void close() throws IOException; }
The functions of these two interfaces are to provide methods for reading characters and closing resources respectively.
Application scenario cases
Reader class is usually used to read data from text files. For example, the BufferedReader we often use is a subclass of the Reader class and is used to read data in text files line by line. In addition, Reader can also be used in scenarios such as reading network data and reading console input.
The following are several application scenarios using the Reader class, for students’ reference only:
1. Read text file
It is common to use the FileReader class to read text files. For example, you can use and combination to read a text file and output it line by line: FileReader
BufferedReader
//1. 读取文本文件 public static void testReadFile(){ FileReader fileReader; BufferedReader bufferedReader; try { fileReader = new FileReader("./template/fileTest.txt"); bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } fileReader.close(); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } }
Through the above case, we demonstrated it locally, and the results can be seen as follows:
2. Read network resources
You can use the InputStreamReader and URL classes to read network resources, for example:
//2. 读取网络资源 public static void testReadURL() throws IOException { URL url = new URL("https://www.baidu.com/"); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); isr.close(); is.close(); } public static void main(String[] args) throws IOException { testReadURL(); }
Through the above case, we demonstrated it locally, and the results can be seen as follows:
3. Read the string
You can use the StringReader class to convert a string into a character stream, for example:
//3. 读取字符串 public static void testReadStr() throws IOException { String str = "Hello, World!!!"; StringReader stringReader = new StringReader(str); int data; while ((data = stringReader.read()) != -1) { System.out.print((char) data); } stringReader.close(); } public static void main(String[] args) throws IOException { testReadStr(); }
Through the above case, we demonstrated it locally, and the results can be seen as follows:
By introducing and demonstrating the above three common application scenarios of using the Reader class in Java, various types of character stream data can be easily read by using subclasses of the Reader class. If you have more cases that are relevant to your life or work, please feel free to share them in the comment area. Having fun alone is not as good as having fun with everyone.
Advantages and Disadvantages
advantage
Reader
The class supports reading of character streams and can accurately read data in text files.Reader
The class can automatically handle character encoding issues and automatically convert encoding methods when reading files.Reader
Different functions can be implemented through various subclasses of the class, and the use is flexible.
shortcoming
Reader
The class reads data slowly and is not suitable for reading binary data.Reader
The class cannot randomly access the data in the file and can only read line by line, which is less efficient when reading large files.Reader
The use of classes is more cumbersome and requires buffers and other methods to improve reading speed and efficiency.
Introduction to class code methods
Construction method
protected Reader()
The default constructor of the Reader class.
method
public int read() throws IOException
Usage: Read a single character and return the ASCII code of the character. If the end of the stream is reached, -1 is returned.
public int read(char[] cbuf) throws IOException
Purpose: Read character array and return the number of characters read.
public int read(char[] cbuf, int offset, int length) throws IOException
Purpose: Read a character array of specified length and return the number of characters read.
public long skip(long n) throws IOException
Usage: Skip n characters (including spaces) and return the actual number of characters skipped.
public boolean ready() throws IOException
Use: Determine whether characters can be read from the stream, and return true if they can be read.
public boolean markSupported()
Use: Determine whether this stream supports mark() operation. Returns true if supported, false otherwise.
public void mark(int readAheadLimit) throws IOException
Use: Set the mark position and point the pointer in the input stream to the mark position. If the stream does not support the mark() operation, an IOException is thrown.
public void reset() throws IOException
Use: Redirect the pointer in the input stream to the mark position. If the stream does not support the reset() operation, an IOException is thrown.
abstract public void close() throws IOException
Purpose: Close the stream and release all resources associated with it.
test case
The following is a test case for reading a file using the Reader class:
Test code demo
package com.example.javase.io.reader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; /** * @author bug菌 * @version 1.0 * @date 2023/10/19 10:34 */ public class ReaderTest { public static void main(String[] args) throws IOException { File file = new File("./template/fileTest.txt"); Reader reader = new FileReader(file); char[] buffer = new char[1024]; int len; while ((len = reader.read(buffer)) != -1) { System.out.println(new String(buffer, 0, len)); } reader.close(); } }
Test result display
According to the above test case, let's execute the main function to test the character data of the read file. The results are shown in the following screenshot:
By comparing the content output by the console with the original text content, it can be seen that the test case uses the Reader class to read the file content normally.
Code analysis
The above test code uses the Reader class to read character data from the file. The following is a step-by-step analysis of the code to help students speed up their understanding.
First, we create a File object, specify the file path to be read, and then use the class to read the file into memory and return the object. Then use the array as a buffer, read data from it into the buffer, and use a class to convert the buffer data into a string and output it to the console until all the data is read. Finally, close the Reader object and release related resources. The whole reading process is very simple. Have you learned it? FileReader
Reader
char[]
Reader
String
Summary of full text
Reader
This article provides a detailed introduction to classes in Java , including their introduction, source code analysis, application scenario cases, analysis of advantages and disadvantages, method introduction and test cases. Through the study of this article, we can better master the usage method and use classes Reader
reasonably in development .Reader
Summarize
Reader
Class is an abstract class in Java for reading character streams. It has the advantages of reading text data, automatically processing character encoding, and can implement different functions through its subclasses. However, the Reader class reads data slowly, is not suitable for reading binary data, and cannot randomly access data in files. When using Reader
classes, pay attention to using buffers and other methods to improve reading speed and efficiency. Finally, pay attention to closing resources to avoid resource leakage problems.
Appendix source code
All the source codes mentioned above have been uploaded and synchronized in "Gitee" , providing students with one-on-one reference learning to help you master it more quickly.
Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~
Lei Jun announced the complete system architecture of Xiaomi's ThePaper OS, saying that the bottom layer has been completely restructured. Yuque announced the cause of the failure and repair process on October 23. Microsoft CEO Nadella: Abandoning Windows Phone and mobile business was a wrong decision. Both Java 11 and Java 17 usage rates exceeded Java 8 Hugging Face was restricted from accessing. Yuque network outage lasted for about 10 hours and has now returned to normal. The National Data Administration officially unveiled Oracle. Launched Java development extension for Visual Studio Code. Musk: Donate 1 billion if Wikipedia is renamed "Weiji Encyclopedia" USDMySQL 8.2.0 GA