java Foundation (23): Byte Stream, Character Stream

Keywords: Java encoding ascii

1. Byte stream

In the previous learning process, we have been operating files or folders, and did not write any data to the file. Now we're going to start writing data to a file, or reading data from a file.

1.1 byte output stream

OutputStream, an abstract class, is a superclass representing all classes of the output byte stream. The data of operation are bytes, and the basic common function method of output byte stream is defined.

The output stream is defined as a write method, as follows:

1.1.1 FileOutputStream class

 

OutputStream has many subclasses, of which FileOutputStream can be used to write data to files.

The FileOutputStream class, file output stream, is used to write data to the output stream of File.

 

 

Construction method

1.1.2 FileOutputStream class writes data to files

Write the data into a file, and the code demonstrates:

public class FileOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //Requirement: Write data to a file.
        //Create files that store data.
        File file = new File("c:\\file.txt");
        //Create a byte output stream object for manipulating files. Once created, the destination of data storage must be specified.
        //The output stream is for files and is created automatically. If the file exists, it is overwritten.
        FileOutputStream fos = new FileOutputStream(file);
        //Call from the parent class write Method.
        byte[] data = "abcde".getBytes();
        fos.write(data);
        //Close flow resources.
        fos.close();
    }
}

1.1.3 Continuation and Line Breaking in Documents

We directly create objects like new FileOutputStream(file), write data, and overwrite the original file. What should we do if we want to continue writing content in the original file?

Continue to consult the API of FileOutput Stream. It is found that in the constructor of FileOutputStream, a boolean type value can be accepted, and if the value is true, it will continue to be added at the end of the file.

Construction method

 

 

Rewrite data and line feeds to files, code demonstration:

public class FileOutputStreamDemo2 {
    public static void main(String[] args) throws Exception {
        File file = new File("c:\\file.txt");
        FileOutputStream fos = new FileOutputStream(file, true);[Set to write data to a specified file]
        String str = "\r\n"[Line wrap]+"itcast";
        fos.write(str.getBytes());
        fos.close();
    }
}

1.1.4 Processing of IO Exceptions

IO exceptions occurred in the previous code. In practical development, let's demonstrate how to deal with exceptions.

 

public class FileOutputStreamDemo3 {
    public static void main(String[] args) {
        File file = new File("c:\\file.txt");
        //Definition FileOutputStream Quotation
        FileOutputStream fos = null;
        try {
            //Establish FileOutputStream object
            fos = new FileOutputStream(file);
            //Writing data
            fos.write("abcde".getBytes());
        } catch (IOException e) {
            System.out.println(e.toString() + "----");
        } finally {
            //Be sure to judge fos Whether it is null,Only not. null Only then can resources be shut down
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException("");
                }
            }
        }
    }
}

 

1.2 Byte input stream InputStream

 

Through the previous study, we can write out the data in memory to the file, then how to read the data in memory into memory, we can achieve through InputStream. InputStream, an abstract class, is a superclass of all classes representing byte input streams. The basic common function method of byte input stream is defined.

int read(): Read a byte and return it. No byte returns - 1.

int read(byte []): Read a certain number of bytes and store them in the byte array, returning the number of bytes read.

1.2.1 FileInputStream class

InputStream has many subclasses, of which FileInputStream can be used to read the contents of files.

FileInputStream obtains input bytes from a file in the file system.

 

Construction method

1.2.2 the FileInputStream class reads the data read method

When reading the data in the file, call read method to read the data from the file.

 

Read the data from the file, code demonstration:

public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("c:\\file.txt");
        //Create a byte input stream object,It must be clear that the data source is actually the creation of byte read streams and data source associations.
        FileInputStream fis = new FileInputStream(file);
        //Read the data. Use read();Read one byte at a time.
        int ch = 0;
        while((ch=fis.read())!=-1){
            System.out.pr        }intln("ch="+(char)ch);

        // Close resources.
        fis.close();
    }
}

1.2.3 Data read(byte []) method

When reading the data in the file, calling read method can only read one at a time, which is too troublesome. So we can define arrays as temporary storage containers. At this time, we can call overloaded read method, which can read more than one character at a time.

 

 

public class FileInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        /*
         * Demonstrate the second reading method, read(byte []);
         */
        File file = new File("c:\\file.txt");
        // Create a byte input stream object,It must be clear that the data source is actually the creation of byte read streams and data source associations.
        FileInputStream fis = new FileInputStream(file);        
        //Create a byte array.
        byte[] buf = new byte[1024];//Length can be defined as an integer multiple of 1024.        
        int len = 0;
        while((len=fis.read(buf))!=-1){
            System.out.println(new String(buf,0,len));
        }
        fis.close();
    }
}

1.3 Byte Stream Exercise

Now that we know how to read and write files, we need to do more complex operations on this basis. Use the read-write operation to complete the copy of the file.

1.3.1 Copy files

Principle: Read an existing data and write it to another file.

 

 

public class CopyFileTest {
    public static void main(String[] args) throws IOException {
        //1,Clear source and purpose.
        File srcFile = new File("c:\\YesDir\test.JPG");
        File destFile = new File("copyTest.JPG");
        
        //2,Explicit byte stream input stream and source correlation, output stream and destination correlation.
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        
        //3, Read bytes using the read method of the input stream and write them to the destination.
        int ch = 0;
        while((ch=fis.read())!=-1){
            fos.write(ch);
        }
        //4,Close resources.
        fos.close();
        fis.close();
    }
}

The data exchange between the input stream and the output stream of the above code is carried out through the variable ch.

There is a problem with the above copy file, which reads one from the source file at a time, then writes it to the specified file, then reads another character, and then writes another, all the time. The efficiency is extremely low.

1.3.2 Buffer Array Copy Files

The above code copy file efficiency is too low, and frequently read data from the file, and write data, can you read more than one data file into the content at a time, and then write out at a time, this speed will be faster than the previous code.

public class CopyFileByBufferTest {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("c:\\YesDir\test.JPG");
        File destFile = new File("copyTest.JPG");
        // Explicit byte stream input stream and source correlation, output stream and destination correlation.
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        //Define a buffer.
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);// Writes the specified length of data in the array to the output stream.
        }
        // Close resources.
        fos.close();
        fis.close();
    }
}

Chapter 1 Character Stream

After the previous study, we have a basic grasp of the reading and writing operations of documents, byte streams can operate on all data in the operation process, but when we operate on documents with Chinese characters, and need to make processing of Chinese characters?

2.1 Byte Stream Read Character Problem

Use the following procedure to read the file with the file in.   

public class CharStreamDemo {
    public static void main(String[] args) throws IOException {
        //Write Chinese in the document
        writeCNText();
        //Read the Chinese in the file
        readCNText();
    }    
    //Reading Chinese
    public static void readCNText() throws IOException {
        FileInputStream fis = new FileInputStream("c:\\cn.txt");
        int ch = 0;
        while((ch = fis.read())!=-1){
            System.out.println(ch);
        }
    }
    //Writing Chinese
    public static void writeCNText() throws IOException {
        FileOutputStream fos = new FileOutputStream("c:\\cn.txt");
        fos.write("a Wisdom Podcast Welcome".getBytes());
        fos.close();
    }
}

When the above program reads the document containing Chinese, we do not see the specific Chinese, but see some numbers. What is the reason? Since we can't see Chinese, how can we deal with it? To solve this problem, we must study the next character encoding process.

2.2 Character Coding Table

We know that the underlying data of the computer is stored in binary data, and how can all kinds of data in our lives correspond to the binary data stored in the computer?

At this time, Lao Mei and them correspond each character with an integer to form a coding table. Lao Mei's coding table is the ASCII table. One of them is the encoding of various English characters.

Coding table: In fact, it is the correspondence table between characters in life and computer binary.

1. ascii: 7 bits in a byte can be represented. The corresponding bytes are positive. 0-xxxxxxx

2. iso-8859-1: Latin code table latin, using 8 bits for one byte. 1-xxxxxxx negative number.

3. GB2312: Simplified Chinese Code Table. Contains 6000-7000 Chinese and symbols. Represented in two bytes. The first byte of two bytes is a negative number, and the second byte may be a positive number.

GBK: At present, the most commonly used Chinese code table is 20,000 Chinese characters and symbols. Represented in two bytes, part of the text, the first byte begins with 1, and the second byte begins with 0.

GB18030: The latest Chinese code table has not been formally used yet.

4. unicode: International Standard Code Table: No matter what text, it is stored in two bytes.

The char type in Java uses this code table. Char c = a'; takes two bytes.

Strings in Java are parsed according to the system default code table. The default code table for simplified Chinese version strings is GBK.

5. UTF-8: Based on unicode, data can be stored in one byte instead of two bytes, and the code table is more standardized, adding encoding information to each byte header (later searched in the api).

Recognition of Chinese code table: GBK, UTF-8; because recognition of Chinese code table is not unique, it involves the problem of coding and decoding.

For our development; common encoding GBK UTF-8 ISO-8859-1

Text - > (Number): Coding. "abc". getBytes() byte []

(Digital) - > Text: Decoding. byte[] b={97,98,99} new String(b)

2.3 Character input stream Reader

In the above program, when we read files with Chinese characters, we use byte stream to read, so we read every byte. As long as these bytes are looked up in the corresponding encoding table, the corresponding characters can be obtained. Whether the API has provided us with the function stream object, Reader, abstract superclass for reading the corresponding character stream.

 

 

read(): Read a single character and return it

read(char []): Reads data into an array and returns the number of reads.

 

2.3.1 FileReader class

Looking at the API of FileInputStream, we found that FileInputStream was used to read raw byte streams such as image data. To read character streams, consider using FileReader.

Open FileReader's API introduction. Convenient class for reading character files. This constructor assumes that both default character encoding and default byte buffer size are appropriate

Construction method

2.3.2 FileReader reads files containing Chinese

Using FileReader to Read Files Containing Chinese

public class CharStreamDemo {
    public static void main(String[] args) throws IOException {
        //Write Chinese in the document
        writeCNText();
        //Read the Chinese in the file
        readCNText();
    }    
    //Reading Chinese
    public static void readCNText() throws IOException {
        FileReader fr = new FileReader("D:\\test\\cn.txt");
        int ch = 0;
        while((ch = fr.read())!=-1){
            //The coded value corresponding to the output character
            System.out.println(ch);
            //Output character itself
            System.out.println((char)ch);
        }
    }
    //Writing Chinese
    public static void writeCNText() throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\test\\cn.txt");
        fos.write("a Wisdom Podcast Welcome".getBytes());
        fos.close();
    }
}

2.4 Character Output Stream Writer

Since there are stream objects for reading characters, there must be written stream objects. Looking at the API, we find that there is a Writer class, which is an abstract class for writing character streams. It describes the corresponding writing action.

2.4.1 FileWriter class

Looking at the API of FileOutputStream, we find that FileOutputStream is used to write streams of raw bytes such as image data. To write to a character stream, consider using FileWriter.

Open FileWriter's API introduction. Convenient class for writing character files. This constructor assumes that the default character encoding and the default byte buffer size are acceptable.

Construction method

2.4.2 FileWriter writes Chinese to file

Write characters to files, first refresh the stream, then close the stream.

public class FileWriterDemo {
    public static void main(String[] args) throws IOException {
        //Demonstration FileWriter Convenient classes for manipulating files.
        FileWriter fw = new FileWriter("d: \\text\\fw.txt");
        fw.write("Hello, thank you. Good-bye.");//These words must be coded first. They are written to the buffer of the stream.
        fw.flush();
        fw.close();
    }
}

2.5 The difference between flush() and close()?

flush(): refresh the buffered data in the stream to the destination, and after refreshing, the stream can continue to use.

close(): Close the resource, but refresh the data in the buffer to the destination before closing, otherwise lose the data, and then close the flow. Streams are not available. If you write more data, you must refresh as you write. The last refresh can be completed by close and closed.

 

2.6 Character Stream Exercises

2.6.1 Copy text files

Exercise: Copy text files.

Train of thought:

1. Since the text involves the encoding table. A character stream is required.

2. Documents are operated on. It involves hard disks.

3. Do you have a code list? No, by default.

The operation is a file, using the default code table. Which character stream object to use? Convenient classes for manipulating files directly using character streams. FileReader FileWriter

public class CopyTextFileTest {
    public static void main(String[] args) throws IOException {
        copyTextFile();
    }
    public static void copyTextFile() throws IOException {
        //1,Clear source and purpose.
        FileReader fr = new FileReader("c:\\cn.txt");
        FileWriter fw = new FileWriter("c:\\copy.txt");
        //2,In order to improve efficiency. Custom buffer array. Character array.
        char[] buf = new char[1024];
        int len = 0;
        while((len=fr.read(buf))!=-1){
            fw.write(buf,0,len);
        }
        /*2,Loop read and write operations. Low efficiency.
        int ch = 0;
        while((ch=fr.read())!=-1){
            fw.write(ch);
        }
        */
        //3,Close resources.
        fw.close();
        fr.close();
    }
}

Posted by sheen4him on Fri, 11 Oct 2019 02:46:51 -0700