Java basics-I/O (2), java basics I/O

Source: Internet
Author: User

Java basics-I/O (2), java basics I/O

Next, take the study notes. I/O learning, I suddenly found some advantages, as if to operate the computer in the future, especially the files in the computer, you can rarely use the mouse. You can add, modify, or delete a few lines of code. This is just a little bit of my mind for beginners. I believe there are many other things behind IO. Continue Learning ing ....

I. Buffer stream and decoration Mode

The emergence of a buffer stream (Packaging class) increases the efficiency of reading and writing data. It can be used for streaming and enhances the function of streaming Based on the stream. What is the difference between the buffer zone provided by the underlying system? The underlying layer directly exchanges data with the target device. In the packaging class, the encapsulated object is used.

BufferedReader: Read text from the character input stream, buffer each character, so as to achieve efficient reading of characters, arrays and rows.

BufferedReader constructor has two types:

---- BufferedReader (Reader in)

---- BufferedReader (Reader in, int sz) creates a buffer character input stream that uses the default size input buffer.

// Example of BufferedWriter use FileWriter w = new FileWriter ("2.txt"); BufferedWriter bw = new BufferedWriter (w); bw. write ("this is a line of content"); bw. newLine (); // This is the function bw provided by the packaging class. write ("this is another line of content"); bw. flush (); // use a buffer stream. Do not forget flush () bw. close (); // It is equivalent to closing w. After writing this, you do not need to write w again. close ()
// Example BufferedReader uses public static void main (String [] args) throws IOException {List <String> nameList = demo2 (); for (String s: nameList) {System. out. println (s) ;}} static List <String> demo2 () throws IOException {List <String> nameList = new ArrayList <String> (); fileReader r = new FileReader ("C:/Name List .txt"); BufferedReader br = new BufferedReader (r); String str = null; while (str = br. readLine ())! = Null) {nameList. add (str) ;}br. close (); return nameList ;}

Ii. Decoration Design Model

Decorator mode (alias Wrapper): dynamically attaches duties to objects. To expand functions, the Decorator provides a more flexible alternative solution than inheritance. To enhance the functions of existing objects, you can define a class, pass existing objects into the class, and provide enhanced functions based on the functions of existing objects. The custom class is called the decoration class. Decoration Classes usually receive decorated objects through constructor methods, and provide stronger functions based on the functions of decorated objects.

Public class Teste3 {public static void main (String [] args) {Japan japan = new Japan (); NiceJapan niceJapan = new NiceJapan (japan); niceJapan. speak () ;}} class Japan {void speak () {System. out. println ("we are both good students");} class NiceJapan {NiceJapan (Japan) {this. japan = japan;} private Japan japan; // void speak () {System. out. println ("qinglu"); // other actions System. out. println ("Shake your head"); japan. speak (); System. out. println ("Several heads"); System. out. println ("scream a few times ");}}

3. byte stream Overview

Without negative values, the data in each byte is a value between 0 and 255 (because one byte is 8 bits and the maximum value is)

If each byte or several adjacent bytes of data in a file can be expressed as a character, the file can be called a text file, which is a special case of binary.

(You can open a notepad and pull an image into it. It will find a lot of garbled characters. It is a special case of binary. Some information on the image can be displayed on the code table, some cannot be messy. This is because, during byte stream operations, the operation units are in bytes. The operation objects do not necessarily have a code table.

Overview:

1. All byte input stream classes are subclasses of the abstract class InputStream.

Int read () reads a byte of data from the source and returns the byte value.

Int read (byte B []) tries to read byte B. length from the source to B, and returns the actually read Word program

Void close () to close the input stream

2. All byte output stream classes are subclasses of the abstract class OutputStream.

Void write (int n) writes a single byte to the output stream.

Void write (byte B []) writes a byte array to the output stream

Void flush () outputs the content in the buffer and clears the buffer (refresh)

Void close () to close the output stream

3. For example, the byte stream is used to read and write files.

FileOutputStream is used to write streams of raw bytes such as data. To write data to the volume stream, consider using FileWriter.

The write method of FileOutputStream is reloaded as follows:

// Void write (byte [] B) // note that the return type is void

// Void write (byte [] B, int off, int len)

// Void write (int B) writes the specified byte to the output stream of this file.

// Reload the read method of FileInputStream as follows:

// Int read () reads a Data byte from the input stream. Returns the read bytes and-1 to the end.

// Int read (byte [] B) reads data of up to B. length bytes from the input stream into a byte array and returns the number of bytes to the end.

// Int read (byte [] B, int off, int len) reads data of up to len bytes into a byte array from the input stream.

// For a byte stream, each read is a byte. If it is English, exactly one English character corresponds to one byte. If it is Chinese, it may correspond to two bytes.

Static void demo1 () throws IOException {OutputStream out = new FileOutputStream ("c:/file1.txt"); out. write ("abcEnlish China ". getBytes (); // The byte stream can be written out without refreshing. close (); InputStream in = new FileInputStream ("c:/file1.txt"); int ch = 0; while (ch = in. read ())! =-1) {System. out. println (char) ch); // it can be found that, if it is English, it can be displayed, but Chinese characters will be garbled} in. close ();}
// For example, use a byte array to receive static void demo1 () throws IOException {InputStream in = new FileInputStream ("c:/Name List .txt "); byte [] buff = new byte [3]; // 1024 int len = 0; while (len = in. read (buff ))! =-1) {String str = new String (buff, 0, len); System. out. println (str); // garbled characters }}
// Example available uses static void demo2 () throws IOException {InputStream in = new FileInputStream ("c:/Name List .txt"); byte [] buff = new byte [in. available ()]; // in. available (); the number of bytes in the current stream that can be read in. read (buff); System. out. println (new String (buff); in. close ();}
// Example. static void demo3 () throws IOException {InputStream in = new FileInputStream ("C: \ image \ lengtu.jpg"); byte [] buff = new byte [in. available ()]; in. read (buff); OutputStream out = new FileOutputStream ("E:/tuzi.jpg"); out. write (buff); in. close (); out. close ();}

Supplement:

In front, the volume stream has a packaging class.

BufferedReader, BufferedWriter

Byte streams also have packaging classes

BufferedInputStream, BufferedOutputStream

Iv. Conversion stream InputStreamReader and OutputStreamWriter

Convert a byte input stream to a character input stream:

InputStreamReader

Public class InputStreamReader extends Reader

Convert byte output to character output stream:

OutputStreamWriter

Public class OutputStreamWriter extends Writer

1) InputStreamReader

It has four constructors:

InputStreamReader (InputStream in)

InputStreamReader (InputStream in, Charset cs)

InputStreamReader (InputStream in, CharsetDecoder dec) // CharsetDecoder Decoder

InputStreamReader (InputStream in, String charsetName)

2) OutputStreamWriter

It has four constructors:

OutputStreamWriter (OutputStream out) // creates an OutputStreamWriter that uses the default character encoding.

OutputStreamWriter (OutputStream out, CharsetEncoder enc) // creates an OutputStreamWriter that uses the given character set.

OutputStreamWriter (OutputStream out, String charsetName) // creates an OutputStreamWriter that uses the specified character set encoder.

OutputStreamWriter (OutputStream out, String charsetName) // creates an OutputStreamWriter that uses the specified character set.

// For example, use a buffer stream to wrap the conversion stream. Convert the byte stream InputStream in = new FileInputStream ("c:/1.txt"); InputStreamReader inputReader = new InputStreamReader (in ); bufferedReader br = new BufferedReader (inputReader); String str = null; while (str = br. readLine ())! = Null) {System. out. println (str );}
// The example reads data from the keyboard and converts it to uppercase to print out public static void main (String [] args) throws IOException {BufferedReader br = new BufferedReader (new InputStreamReader (System. in); String msg = null; while (msg = br. readLine ())! = Null) {System. out. println (msg. toUpperCase ());}}

5. ByteArrayInputStream and ByteArrayOutputStream

It is used to read and write the content of byte arrays in the form of IO streams, and supports functions similar to memory virtual files or memory image files.

Disabling ByteArrayOutputStream is invalid. Methods In this class can still be called after the stream is closed without generating any IOException.

// ByteArrayInputStream (byte [] buff)

// ByteArrayInputStream (byte [] buff, int offset, int length)

// ByteArrayOutStream () // if no parameter is input, a 32-byte buffer is created by default, and the data in the buffer is written into a byte array. The buffer will automatically increase as data is constantly written. You can use toByteArray () and toString () to obtain data.

// ByteArrayOutStream (int size) creates a Buffer Based on the specified size

// Byte [] toByteArray () of ByteArrayOutStream creates a newly allocated byte array. The size is the current size of the output stream, and the valid content of the buffer has been copied to the array.

 

// Example, use ByteArrayOutputStream byteOut = new ByteArrayOutputStream (); byteOut. write ("This is data in the virtual memory ". getBytes (); byte [] byteArray = byteOut. toByteArray (); String str = new String (byteArray); System. out. println (str );
// Enhance reading characters from the input stream, convert the characters to uppercase, and write them to the public static void main (String [] args) in the output stream) throws IOException {/* Example 1 use ByteArrayInputStream and ByteArrayOutputStream ByteArrayInputStream in = new ByteArrayInputStream ("abcdef ". getBytes (); ByteArrayOutputStream out = new ByteArrayOutputStream (); transform (in, out); byte [] contents = out. toByteArray (); String str = new String (contents); System. out. println (str); * // Example 2 input on the keyboard Output stream transform (System. in, System. out); // Example 3 use the file input and output stream InputStream in = new FileInputStream ("c:/1.txt"); OutputStream out = new FileOutputStream (" e:/big.txt "); transform (in, out);} static void transform (InputStream in, OutputStream out) throws IOException {int ch = 0; while (ch = in. read ())! =-1) {out. write (Character. toUpperCase (ch ));}}

 

Related Article

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.