Java basic review: Ghost stream

Source: Internet
Author: User

The characters in Java are Unicode encoded and dual-byte, that is, a character is equal to two bytes.

The advantage of ghost stream is that it can operate text files more conveniently.

(Abstract stream) character output stream: Writer character input stream: Reader

 

Package day1_charstream; import java. io. file; import java. io. fileReader; import java. io. IOException; import java. io. reader; public class Demo1 {public static void main (String [] args) {File file = new File ("d:/Test/hi.txt"); read (file ); // read Chinese garbled characters}/*** read the specified file and print it out on the screen, and use the automatic close resource * @ param file */public static void read (File file) {try (Reader r = new FileReader (file );) {char [] buff = new char [1024]; int len = 0; while (len = r. read (buff ))! =-1) {String data = new String (buff, 0, len); System. out. println (data) ;}} catch (IOException e) {e. printStackTrace ();}}}

Differences between byte stream and byte stream:

1) the buffer zone will be used when the byte stream operation is used, while the byte stream operation will not use the buffer zone.

2) during output, the OutputStream class can be output even if the content is not closed at the end. However, if it is a Writer, if it is not closed, the last piece of content cannot be output, because all the content is saved in the buffer, and every time close () is called () the method indicates clearing the buffer. It can be proved that the swap stream actually uses the buffer:
Byte stream: Program → File
Protocol stream: Program → buffer → File
3) compared with the two, byte streams are certainly more convenient, and in the program, pictures and MP3 files are saved in bytes, it is certain that byte streams are more widely used than bytes streams.
However, it should be noted that if you want to operate Chinese characters, the stream is definitely the best.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.