Java Convert StreamInputStreamReader
1. Introduction to InputStreamReader
InputStreamReader is a class in the package that inherits the class.
Its main function is to convert the byte input stream into a character input stream.
When performing file read and write operations, if you encounter a different encoding format, you can use InputStreamReader to process it.
2. InputStreamReader construction method
InputStreamReader provides the following two constructors:
- (1) InputStreamReader(InputStream in) Create an InputStreamReader instance using the default character set.
- (2) InputStreamReader(InputStream in, Charset cs) Create an InputStreamReader instance using the specified character set.
3. Common methods of InputStreamReader
Here are some common methods of InputStreamReader:
- (1) int read() reads a character and returns the read character. If the end of the file is reached, it returns -1.
- (2) int read(char[] cbuf, int offset, int length) Read characters into part of the array, returns the number of characters read, and if the end of the file is reached, return -1.
- (3) boolean ready() determines whether the InputStreamReader is ready to read data.
- (4) void close() close InputStreamReader and release relevant resources.
4. Code examples and running results
Here is a simple example that demonstrates how to read a text file using InputStreamReader:
import ; import ; import ; public class InputStreamReaderExample { public static void main(String[] args) { try { // Create FileInputStream instance FileInputStream fis = new FileInputStream(""); // Create an InputStreamReader instance, using the default character set InputStreamReader isr = new InputStreamReader(fis); // Read file content int data; while ((data = ()) != -1) { ((char) data); } // Close the stream (); (); } catch (IOException e) { (); } } }
Assume that the file content is as follows:
Hello, World!
Hello World!
Run the above code and the output result is as follows:
Hello, World!
Hello World!
Next, we read the file using the specified character set:
import ; import ; import ; import ; public class InputStreamReaderExample2 { public static void main(String[] args) { try { // Create FileInputStream instance FileInputStream fis = new FileInputStream(""); // Create an InputStreamReader instance, specifying the character set to UTF-8 InputStreamReader isr = new InputStreamReader(fis, ("UTF-8")); // Read file content int data; while ((data = ()) != -1) { ((char) data); } // Close the stream (); (); } catch (IOException e) { (); } } }
The run result is the same as in the previous example because the file is encoded in UTF-8.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.