The difference between java byte stream and character stream

The difference between java byte stream and character stream (reproduced)

Reprinted from: https://blog.csdn.net/sunhuaqiang1/article/details/52756999

  The use of byte stream and character stream 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, it is directly operated by the file itself, while the character stream uses the buffer when operating, and then operates the file through the buffer, as shown in the following figure. 

write picture description here

The following two operations of writing files are mainly compared, but the output stream is not closed after the operation of the byte stream and the character stream is completed. 

Example: Using a byte stream without closing the execution

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数组
     byte b[] = str.getBytes();          
// 将内容输出,进行写操作 
     out.write(b);    
// 第4步:关闭输出流(此时没有关闭)    
    // out.close();                   
        }    
} 

  Program running result: 

write picture description here

  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. The following continues to use the character stream to complete, and then observe the effect. 
Example: Using a character stream to execute without closing

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();              
    }    
}   

Program running result: 

write picture description here

 After the program runs, it 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 forced to be output, but if the program is not closed, the buffer The contents of the area 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? 
  Answer: A buffer can be simply understood as a special memory area. 
  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. 
  Example: Forcibly emptying the buffer

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();                  
    }    
}   

 Program running result: 

write picture description here

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? 
  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 the way they are handled 
stream classification:

  • 1. Java byte stream

    InputStream is the ancestor of all byte input streams, and OutputStream is the ancestor of all byte output streams.

  • 2. Java character stream

    Reader is the ancestor of all input streams that read strings, and writers are the ancestor of all output strings. 
      InputStream, OutputStream, Reader, writer are all 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[], byte[] String.getBytes(String charsetName) is the same. As for java.io, there are many other streams, mainly to improve performance and ease of use, such as BufferedInputStream, PipedInputStream and so on.

Note:

  In Java, its kernel uses Unicode, which means it remembers the Unicode internal encoding for each character. Not compatible with ANSI codes. 
  According to the ANSI coding standard, punctuation marks, numbers, uppercase and lowercase letters all occupy one byte, and Chinese characters occupy 2 bytes. According to the UNICODE standard, all characters occupy 2 bytes. 
  Because characters in Java use the Unicode encoding standard, the string "Learn Java" occupies 10 bytes in the Java language. 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324110383&siteId=291194637