[Java IO stream] example explanation of byte stream and character stream

Byte stream and character stream

There must be read and write operations for files. Read and write correspond to input and output streams, which are divided into byte and character streams.

1. In terms of file operation, there are read and write operations - that is, input and output.

2. In terms of flow direction, there are input and output.

3. In terms of stream content, there are bytes and characters.

This article explains the input and output operations of byte stream and character stream in io stream.

1、 Byte stream

1) Input and output streams

First, the byte stream needs to be read and written, that is, input and output, so it has two abstract parent classes InputStream and OutputStream.

InputStream abstracts the way applications read data, that is, input stream. OutputStream abstracts the way an application writes data, that is, the output stream.

2) End of reading and writing

In the byte stream, when reading and writing ends and reaches the end of the file, it is called EOF = end or read to - 1 to the end.

3) Basic methods of input stream

First, we need to know what the input stream is. For example, when we input content on a text file through our keyboard, the keyboard acts as an input stream rather than an output stream. Because the function of the keyboard is to input the content into the system, and then the system writes it to the file. The following is the basic method of input stream read():

Where in is an instance of the InputStream abstract class. It can be found that this method is similar to the read () method in the RandomAccessFile class, because both are read through bytes.

4) Basic method of output stream

The output stream is a write operation. Its basic operation method is write (). This method can be corresponded with the input read () method one by one for better understanding.

After understanding the basic operation methods of InputStream and OutputStream, let's take a look at their "children" FileInputStream and fileoutputstream.

These two subclasses specifically implement the operations of reading and writing data on files. These two classes are more used in schedule programming.

2、 Use of FileInputStream and fileoutputstream classes

-----------------Use of FileInputStream class

1. Use the read () method to read the file

Run results (tested by any file):

be careful:

The fileinputstream() constructor can be constructed by file name (string) or file object. The above case is constructed using file name.

(b=in.read())!=- 1 judge whether to read the end of the file by reading - 1.

in. Close() objects that use the IO stream must close the stream. It is important to develop good habits.

2. Use the read (byte [] buf, int size) method to read the file

The above method can only read one byte at a time. It is too inefficient for large files. It is recommended to use this method to read files at one time.

Read (byte [] buf, int size) returns the number of bytes read, that is, the effective length of the buf byte array, so the length used when outputting the buf array is count instead of buf Length, because we do not know the relationship between the file size and the array size. The above method is applicable to reading the file content into the array at one time when the file size does not exceed the array size. There is a problem here. If the file size exceeds the array size, how can we read all the files??

We know that reading - 1 means reading the end of the file, so we still use the while loop to repeat the reading until reading - 1 ends the loop. Modify the above code as follows:

Well, let's test the results with a file larger than the array (too long, only at the end of the screenshot):

You can compare the differences between the two. The second optimization is more suitable for daily use, because we can read it directly at one time regardless of the file size.

-----------------Use of fileoutputstream class

The use of fileoutputstream class is similar to that of FileInputStream class. It implements the method of writing btye data to a file. Some of the details are similar to FileInputStream. I won't mention them. You can understand them.

1. Construction method

During the construction of fileoutputstream class, different methods can be used according to different situations, such as:

2. Use the write () method to write the file

The write () method is similar to read (). It can only operate on one byte, that is, it can only write one byte. For example:

It is obviously inefficient to write only one byte at a time. Of course, like InputStream, OutputStream can directly operate on byte arrays.

3. Use the write (byte [] buf, int size) method to write the file

Meaning: write the byte [] array from the start position to the end length of the size position to the file.

The syntax format is the same as that of read, without much explanation

3、 Combined case of FileInputStream and fileoutputstream

I learned how to use InputStream and OutputStream. This time, I combined them to write a method to copy files.

Test file case:

Operation results:

Copy succeeded!

4、 Use of datainputstream and dataoutputstream

Datainputstream and dataoutputstream are extensions to the "stream" function, which makes it easier to read int and long. Characters and other types of data.

For dataoutputstream, it has some more methods, such as

writeInt()/wirteDouble()/writeUTF()

These methods are essentially completed through the write () method. These methods are packaged for our convenience.

1. Construction method

Taking dataoutputstream as an example, the objects in the construction method are objects of OutputStream type, which can be used by constructing fileoutputstream objects.

2. Use of write method

3. Use of read method

In contrast to the above writing method, look at the following example to read the file just written

Operation results:

Summary: datainputstream and dataoutputstream are actually wrappers of FileInputStream and fileoutputstream. Through nesting, we can use the read and write operations of FileInputStream and fileoutputstream. They also have many other methods. You can query the API.

Note: errors will occur if the types do not match when reading!

5、 Bufferedinputstresam & bufferedoutputstresam for byte stream

These two stream classes provide buffered operations for Io. Generally, buffering will be added when opening files for write or read operations. This stream mode improves the performance of Io.

Putting input into a file from the application is equivalent to pouring one cylinder of water into another:

The fileoutputstream - > write () method is equivalent to "transferring" water drop by drop

Dataoutputstream - > write() XXX method will be more convenient, which is equivalent to "transferring" water one by one

Bufferedoutputstream - > write method is more convenient. It is equivalent to putting a ladle of water into a bucket (buffer zone) first, and then pouring it from the bucket into a cylinder. It improves the performance and is recommended!

The above mentioned case of a copy file written in combination with FileInputStream and fileoutputstream. This time, the above case is modified through byte buffer stream to observe the differences, advantages and disadvantages of the two.

Main function test:

(1) Single byte file copy, using buffered byte stream

Operation results (efficiency):

(2) Single byte unbuffered file copy

Operation results (efficiency):

(3) Batch byte for file copy, unbuffered byte stream (the code of the initial case in point 3 above)

Operation results (efficiency):

(4) Batch byte for file copy, buffered byte stream (the most efficient, recommended!!)

Operation results (efficiency):

be careful:

Read or write bytes in batches. Buffered streams with bytes are the most efficient. This method is recommended.

When the byte buffer stream is used, the buffer must be flushed after the write operation, flush ().

When the byte buffer stream is not used, flush () may not be added, but it is better to add it.

6、 Character stream

First, we need to understand the following concepts.

1) Need to understand coding problems ----- > transfer to coding problems in computers

2) Understanding text and text files

Java text (char) is a 16 bit unsigned integer, which is the Unicode encoding of characters (double byte encoding)

The file is byte byte Data sequence of

Text file is the storage of serialized bytes of text (char) sequence according to some coding scheme (UTF-8, utf-16be, GBK)

3) Character stream (reader writer)

Character processing, one character at a time;

The bottom layer of the character is still the basic byte sequence;

4) Basic implementation of character stream

Inputstreamreader: parse byte stream into char stream according to code.

Outputstreamwriter: provides char stream to byte stream, which is processed according to encoding.

-------------------------Basic use of reader and writer-------------------------------

be careful:

Character stream operates on text files, and cannot operate on other types of files!!

By default, it is parsed according to GBK code (the default code of the project). When operating a text file, write the coding format of the file itself (add the coding format after the constructor)!!

The difference between character stream and byte stream is mainly due to the different operation objects. In addition, character stream reads and writes files in character units, while byte stream operates in bytes or byte arrays!!

When using character stream, pay extra attention to the encoding format of the file. If you are not careful, it will cause garbled code!

7、 Character stream file read / write streams filewriter and FileReader

Similar to the FileInputStream and fileoutputstream classes of byte stream, character stream also has corresponding file read-write streams filewriter and FileReader classes, which are mainly used to read and write text files.

FileReader / filewriter: the path where the file name can be written directly.

Compared with inputstreamreader, it has disadvantages: it cannot specify the read and write codes, and is prone to garbled codes.

Note: FileReader and filewriter cannot add encoding parameters, so when the encoding of the project and the read file is different, garbled code will be generated. In this case, only inputstreamreader and outputstreamwriter can be regressed.

8、 Filter BufferedReader & bufferedwriter for character stream

The filters for character streams are BufferedReader and bufferedwriter / printwriter

In addition to the basic reading and writing functions, they also have some special functions.

BufferedReader -- > readLine reads one line at a time and does not recognize newline bufferedwriter -- > write writes one line at a time. Newline printwriter is often used with BufferedReader. Newline writing is more convenient than bufferedwriter

Definition method:

usage method:

Here, we can use printwriter instead of bufferedwriter to write. Printwriter has many advantages over bufferedwriter:

The constructor is convenient, concise and flexible

You can choose whether to flush automatically during construction

The println () method can be used to realize automatic line feed, which is more convenient to use with BufferedReader

usage method:

be careful:

You can use the readLine () method of BufferedReader to read in one line at a time in the form of string, and use null to judge whether to read to the end.

Use the write () method of bufferedwriter to write the file. After each write, you need to call the flush () method to clear the buffer; Printwriter can specify automatic flush during construction without calling the flush method.

When writing, you need to notice that the data in the written data will be lost. You can call the newLine () method of BufferedReader or replace the println () method with PrintWriter after each write.

Printwriter is usually used with bufferedwriter. (the construction method and use method of printwriter are simpler).

The above example explanation of [Java IO stream] byte stream and character stream is all the content shared by Xiaobian. I hope it can give you a reference and support more programming skills.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>