Difference between byte stream and character stream in java

Preface:
The use of byte streams and character streams is very similar. Are there any other differences between the two except for the difference in operation code.
In fact, the byte stream itself does not use the buffer (memory) when operating, and is directly operated by the file itself, while the character stream uses the buffer when operating, and then operates the file through the buffer.


Use byte streams to execute without closing:

package org.lxh.demo12.byteiodemo;    
import java.io.File;    
import java.io.FileOutputStream;    
import java.io.OutputStream;    
public class OutputStreamDemo05 {    
public static void main(String[] args) throws Exception {   // 异常抛出,  不处理    
// 第1步:使用File类找到一个文件    
    File f = new File("d:" + File.separator + "test.txt"); // 声明File  对象    
// 第2步:通过子类实例化父类对象    
    OutputStream out = null;            
// 准备好一个输出的对象    
    out = new FileOutputStream(f);      
// 通过对象多态性进行实例化    
// 第3步:进行写操作    
    String str = "Hello World!!!";      
// 准备一个字符串    
    byte b[] = str.getBytes();          
// 字符串转byte数组    
    out.write(b);                      
// 将内容输出    
// 第4步:关闭输出流    
   // out.close();                  
// 此时没有关闭    
       }    
   }

Program running result:

hello world!!!

At this time, the byte stream operation is not closed, but the output content still exists in the file, which proves that the byte stream directly manipulates the file itself. And the following continues to use the character stream to complete, and then observe the effect:

Use a character stream without closing the execution:

package org.lxh.demo12.chariodemo;    
import java.io.File;    
import java.io.FileWriter;    
import java.io.Writer;    
public class WriterDemo03 {    
   public static void main(String[] args) throws Exception { // 异常抛出,  不处理    
       // 第1步:使用File类找到一个文件    
       File f = new File("d:" + File.separator + "test.txt");// 声明File 对象    
       // 第2步:通过子类实例化父类对象    
       Writer out = null;                 
// 准备好一个输出的对象    
       out = new FileWriter(f);            
// 通过对象多态性进行实例化    
       // 第3步:进行写操作    
       String str = "Hello World!!!";      
// 准备一个字符串    
       out.write(str);                    
// 将内容输出    
       // 第4步:关闭输出流    
       // out.close();                   
// 此时没有关闭    
   }    
}

Running result:
After the program runs, you will find that there is no content in the file, this is because the buffer is used when the character stream is operated, and when the character stream is closed, the content in the buffer is forcibly output. But if the program is not closed, the contents of the buffer cannot be output, so it is concluded that the character stream uses the buffer, and the byte stream does not use the buffer.
Question: What is a buffer zone?
The term buffer is encountered in many places, so what is a buffer? What's the use?

回答:缓冲区可以简单地理解为一段内存区域。

A buffer can be simply understood as a special piece of memory.
In some cases, if a program frequently operates a resource (such as a file or database), the performance will be very low. At this time, in order to improve performance, a part of the data can be temporarily read into an area of ​​memory, and then directly It is enough to read data from this area, because the reading speed of memory will be faster, which can improve the performance of the program.

In the operation of the character stream, all characters are formed in the memory, and all the content will be temporarily saved in the memory before output, so the buffer is used to temporarily store the data.

If you want to output all the contents of the character stream without closing it, you can use the flush() method in the Writer class to complete it.

Forcibly empty the buffer:

package org.lxh.demo12.chariodemo;    
import java.io.File;    
import java.io.FileWriter;    
import java.io.Writer;    
public class WriterDemo04 {    
   public static void main(String[] args) throws Exception { // 异常抛出不处理    
       // 第1步:使用File类找到一个文件    
       File f = new File("d:" + File.separator + "test.txt");// 声明File    
对象    
       // 第2步:通过子类实例化父类对象    
       Writer out = null;                   
// 准备好一个输出的对象    
       out = new FileWriter(f);             
// 通过对象多态性进行实例化    
       // 第3步:进行写操作    
       String str = "Hello World!!!";      
// 准备一个字符串    
       out.write(str);                    
// 将内容输出    
       out.flush();                       
// 强制性清空缓冲区中的内容    
       // 第4步:关闭输出流    
       // out.close();                
// 此时没有关闭    
   }    
}

operation result:

hello world!!!

At this point, the content already exists in the file, which further proves that the content is saved in the buffer. This point should be paid special attention to in the future development of readers.

Question: Is it better to use a byte stream or a character stream?
After learning the basic operations of byte stream and character stream, you have roughly understood the differences in the operation process. So is it better to use byte stream or character stream in development?

Answer: It is better to use a byte stream.
Before answering, let the reader explain such a concept. All files are stored in bytes on the hard disk or during transmission, including pictures, etc., and characters are only stored in bytes. It will be formed in memory, so in development, byte streams are widely used.

The main difference between byte streams and character streams is how they are handled

Stream classification:
1. Java's byte stream: InputStream is the ancestor of all byte input streams, and OutputStream is the ancestor of all byte output streams.
2. Java's character stream: Reader is the ancestor of all read string input streams, and writer is the ancestor of all output strings.
Note: InputStream, OutputStream, Reader, Writer are abstract classes. So it can't be new directly.

Byte stream is the most basic, all subclasses of InputStream and OutputStream are, mainly used to process binary data, it is processed by bytes. But in practice, a lot of data is text, and the concept of character stream is proposed, which is processed according to the encode of the virtual machine, that is, character set conversion.

The two are associated with InputStreamReader, OutputStreamWriter, and are actually associated with byte[] and String. The problem of Chinese characters in actual development is actually caused by the inconsistency of conversion between the character stream and the byte stream

When converting from a byte stream to a character stream, in fact, when byte[] is converted to String,
public String(byte bytes[], String charsetName)
has a key parameter character set encoding, which we usually omit, then the system Just use the lang of the operating system. When the character stream is converted into a byte stream, in fact, when String is converted into byte[],
the same is true for byte[]String.getBytes(String charsetName)

As for java.io, there are many other streams, mainly to improve performance and ease of use,
such as BufferedInputStream, PipedInputStream and so on.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325860172&siteId=291194637