“This is the 8th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

The vast sea of thousands of thousands, thank you for this second you see here. Hope my article is helpful to you!

Wish you in the future, keep love, go to the mountains and seas!

Characters of the flow

Yesterday we learned about byte streams. We’ve learned all about byte streams, but for IO streams, we need to learn about another type of stream — character streams.

The character stream can also be divided into character input stream and character output stream, so today we are ready to have a detailed understanding of character input stream!

Character I/O stream and byte I/O stream have the same functions, but the way to transmit data is different. Byte stream transmits data in bytes, and can make any type of data, such as text, audio, video, picture, etc. A character stream transmits data in character units and can only transmit text data. The advantage of using character I/O streams is that there is no garbled code problem when reading Chinese, whereas there is no guarantee of this when using byte I/O streams. Because a Chinese character may occupy more than one byte of storage.

What’s going to happen? Let’s see. Is there a way to fix it?

public class CharaterTest {
    public static void main(String[] args) throws IOException {
        //FileInputStream Is a character input stream for manipulating files
        FileInputStream fis = new FileInputStream("E:\\demo\\testTxt.txt");

        int len;
        while((len = fis.read()) ! = -1) {
            System.out.print((char) len); } fis.close(); }} Hello ±±¼« D CIoAa ·¢³ oEO æ µ AAIiCopy the code

This is… What are they? I bet you’re wondering if I’m ripping you off, if I wrote that on purpose? Of course, no, like me so kind, pure, simple set of excellent qualities for a body such a person, will pit you? Let’s take a look at my file information.

This is because, when a byte stream reads a Chinese character, it may not display the full character because a Chinese character consumes multiple bytes of storage. But, but, I can’t use a byte stream to read, so how else can I read?

Methods are certainly there, but for reading Chinese, not particularly convenient, and later we will also learn the character stream, this for reading Chinese, especially convenient, for this kind of plain text, the preferred is the character stream.

Let’s see what we can do first, shall we

public class CharaterTest2 {
    public static void main(String[] args) throws IOException {
        //FileInputStream Is a character input stream for manipulating files
        FileInputStream fis = new FileInputStream("E:\\demo\\testTxt.txt");

        byte[] b = new byte[1024];
        int len = 0;
        while((len = fis.read(b)) ! = -1){
            System.out.print(new String(b, 0, len)); } fis.close(); }} Hello, North Star is sending you a video chatCopy the code

Can read, you say, if the goddess suddenly sent a message to find you video chat, but your computer or mobile phone display is a bunch of gibberish, your head is a bunch of questions.

Maybe you are still wondering what the goddess sent, is not scolding you. But maybe this is your missed opportunity to have a goddess, so learn Java well.

Back to the topic, why can use String to display normally, don’t worry, let me show you a look.

public String(byte bytes[], int offset, int length) {
    checkBounds(bytes, offset, length);
    this.value = StringCoding.decode(bytes, offset, length);
}

static char[] decode(byte[] ba, int off, int len) {
    ....  
}
Copy the code

You can see that the String constructor, which has the decode function, defaults to UTF-8, which is the current default encoding. If everything is garbled through the String constructor, it means that maybe your text isn’t UTF-8, maybe it’s GBK or ANSI or something like that. More on how to solve the encoding problem later. For now, here’s how:

Think of it this way: Character stream = byte stream + encoding table.

Parent class of character input stream (Reader)

Reader is the parent class of all input character streams and is an abstract class. The main function is to read character information into memory. It defines the basic common function methods for character input streams.

architecture

  • InputStreamReaderIs a bridge between a byte stream and a character stream that reads bytes and decodes them into characters using the specified character set.
  • FileReader Is a convenience class for reading character files. The system default character encoding and default byte buffer are used for construction.
  • BufferedReader Character buffer stream, which reduces the number of I/OS and improves the reading and writing efficiency.
  • FilterReader Is the parent class of all custom concrete decorator streams.

Methods in Reader

After we learn about byte streams, we can see that all input streams in an IO stream have the same read(). Subsequent subclasses of the character input stream have these methods, requiring the read() method to read the file and the close() method to close the resource.

FileReader

1. Construction method
  • Public FileReader(File File) : Creates a new FileReader, given the File object to read.

  • Public FileReader(String fileName) : Creates a new FileReader, given the name of the file to read.

    Create a code demo:

    public class FileReaderTest {
        public static void main(String[] args) throws FileNotFoundException {
    
            // Use the File object to create the stream object
            File file = new File("e:\\demo\\a.txt");
            FileReader fr = new FileReader(file);
    
            // Create the stream object using the file name
            FileReader fr2 = new FileReader("e:\\demo\\b.txt");
            
            //FileReader fr3 = new FileReader("e:\\demo\\c.txt");
            // If the file cannot be read, an exception will be reported.
            / / the Exception in the thread "is the main" Java. IO. FileNotFoundException: e: \ demo \ c.t xt (system could not find the file specified.)}}Copy the code

    As you can see, similar to the way byte streams are created, an exception is reported when the file cannot be read.

2. Read character data

Character streams are used to read text files, so let’s test this:

  1. Public int read() : reads data one character at a time, promotes to int, reads to the end of the file, returns -1. You can test that, as with byte streams, if you read no data, you will return -1. Read directly using a loop:

    public class ReaderTest {
        public static void main(String[] args) throws IOException {
            // Create the stream object using the file name
            FileReader fr = new FileReader("e:\\demo\\testTxt.txt");
            // Define variables to hold data
            int ch = 0;
            // Loop read
            //public int read()
            while((ch = fr.read())! = -1) {
                System.out.print((char) ch);
            }
            // Close the resourcefr.close(); }} Hello, North Star is sending you a video chatCopy the code

    Note:

    • I’m going to read the same thing hereint Type, which requires strong conversion to character type. Is displayed as the original file.
    • Once again, you have to shut down resources.
  2. Public int read(char cbuf[]) public int read(char cbuf[]) public int read(char cbuf[]) public int read(char cbuf[]) public int read(char cbuf[]) Use the loop directly to demonstrate:

    public class ReaderTest2 {
        public static void main(String[] args) throws IOException {
            // Create the stream object using the file name
            FileReader fr = new FileReader("e:\\demo\\testTxt.txt");
            // Define a variable to hold the number of valid characters
            int len = 0;
            // Define a character array as a container for character data
            char[] cbuf = new char[2];
            // Loop read
            //public int read(char cbuf[])
            while((len = fr.read(cbuf)) ! = -1) {
                System.out.println(new String(cbuf));
            }
            // Close the resourcefr.close(); }} Program execution result: The North Star sends you a video chatCopy the code

    As you can see, he still has one more character, which is the same problem as the byte input stream, so let’s use getting the valid character improvement:

    public class ReaderTest3 {
        public static void main(String[] args) throws IOException {
            // Create the stream object using the file name
            FileReader fr = new FileReader("e:\\demo\\testTxt.txt");
            // Define a variable to hold the number of valid characters
            int len = 0;
            // Define a character array as a container for character data
            char[] cbuf = new char[2];
            // Loop read
            //public int read(char cbuf[])
            while((len = fr.read(cbuf)) ! = -1) {
                System.out.println(new String(cbuf, 0, len));
            }
            // Close the resourcefr.close(); }} Program execution result: Polaris sends you a video chatCopy the code

    Summary:

    It turns out that most of the methods we’ve used in byte streams are pretty much the same. For plain text, a character stream is preferred, while in other cases a byte stream is used.

conclusion

I believe you have a certain understanding of the IO stream character input stream class, looking forward to waiting for the next chapter of the character output stream teaching!

Of course, there are many streams waiting to watch together next time! Welcome to the next chapter!

So far, the world is closed for today, good night! Although this article is over, BUT I still, never finished. I will try to keep writing articles. The coming days are long, and the horse is slow!

Thank you for seeing this! May you be young and have no regrets!

Note: If there are any mistakes and suggestions, please leave a message! If this article is also helpful to you, I hope you give a lovely and kind attention, thank you very much!