Java Foundation--io (ii)

Source: Internet
Author: User

Then the previous article, continue to do the study notes. Learn IO this piece, suddenly found a little advantage, as if after the operation of the computer, especially the computer files what, you can use the mouse very little. Add, modify, delete what, a few lines of code can be done. This is just a little bit of a beginner's mind, I am the big use of Io, I believe there are many. Continue to learn ing ....

First, buffer flow and decorative mode

Buffer Stream (wrapper class), the presence of buffers increases the efficiency of data read and write, it can be used for convection packaging, on the basis of the flow of convection function is enhanced. What is the difference between the buffers provided by the underlying system? The underlying direct and target devices exchange data, wrapping the class, through the wrapped object.

BufferedReader: Reads text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.

There are two constructor functions for BufferedReader:

----BufferedReader (Reader in)

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

// Example  The use of BufferedWriter FileWriter w=new FileWriter ("2.txt"); BufferedWriter BW=new  BufferedWriter (w);    Bw.write ("This is a line of content");    Bw.newline ();   // This is the functionality provided by the wrapper class    Bw.write ("This is another line of content");    Bw.flush ();   // with a buffered stream, do not forget to flush ()    Bw.close ();  // It's equivalent to closing W, so after that, you don't have to write W.close ().
//example of the use of BufferedReader Public Static voidMain (string[] args)throwsIOException {List<String> namelist=Demo2 ();  for(String s:namelist) {System.out.println (s); }}            StaticList<string> Demo2 ()throwsIOException {List<String> namelist=NewArraylist<string>(); FileReader R=NewFileReader ("List of c:/. txt"); BufferedReader BR=NewBufferedReader (R); String Str=NULL;  while((Str=br.readline ())! =NULL) {namelist.add (str);    } br.close (); returnNameList;}

Second, decorative design mode

Decorator Mode (alias wrapper): Dynamically attaches responsibilities to objects, and to extend functionality, decorators provide a more resilient alternative than inheritance. When you want to enhance an existing object, you can define a class, pass in an existing object, base on the functionality of an existing object, and provide enhanced functionality. Then the custom class is called the adornment class. The adornment class usually receives the decorated object through the construction method, and provides stronger function based on the function of the decorated object.

 Public classTeste3 { Public Static voidMain (string[] args) {Japan Japan=NewJapan (); Nicejapan Nicejapan=NewNicejapan (Japan);        Nicejapan.speak (); }}classjapan{voidspeak () {System.out.println ("We're all good students."); }}classnicejapan{Nicejapan (Japan Japan) { This. japan=Japan; }    PrivateJapan Japan;//Combination    voidspeak () {System.out.println ("Clear throat");//Other ActionsSystem.out.println ("Shake Your Head");    Japan.speak (); System.out.println ("Knock a few heads."); System.out.println ("A few screams,"); }}

Iii. Overview of the byte stream

In cases where negative numbers are not considered, the data in each byte is a value between 0-255 (because one byte is 8 bits and the maximum is 255)

If each byte in a file or several bytes of data can be represented as a character, you can refer to this file as a text file, which is a special case of binary binary.

(You can open a Notepad, and then pull a picture in, you will find a lot of garbled, it is a special case of binary, the information on the picture can be displayed with the Code table on the pair, some can not be chaotic.) This is because, when a byte-stream operation is performed, the operating unit is not necessarily a code table corresponding to the operation of the object in bytes.

Overview:

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

int read () reads a byte of data from the source, returning the byte value

int read (byte b[]) attempts to read from the source b.length bytes to B, returning the actual read of a Word program

void Close () to close the input stream

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

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

void write (Byte b[]) writes an array of bytes to the output stream

void Flush () outputs the contents of the buffer and empties the buffer (refresh)

void Close () to close the output stream

3. Example, using a byte stream to read and write files

FileOutputStream a stream used to write raw bytes such as data. To write a character stream, consider using FileWriter.

Several overloaded forms of the FileOutputStream write method are as follows:

void Write (byte[] b)//Note the return type is void

void Write (byte[] b, int off, int len)

void write (int b) writes the specified bytes to this file output stream.

Several overloaded forms of the FileInputStream read method are as follows

int read () reads a byte of data from this input stream. Returns the read byte to the end of the return-1

int read (byte[] b) reads up to b.length bytes of data from this input stream into a byte array and returns the number of bytes returned to the tail-1

int read (byte[] b, int off, int len) reads a maximum of Len bytes of data from this input stream into a byte array.

For a byte stream, every time a read is a bytes, if it is in English, just one byte in English, if Chinese, it might correspond to two bytes

Static voidDemo1 ()throwsioexception{OutputStream out=NewFileOutputStream ("C:/file1.txt"); Out.write ("Abcenlish China". GetBytes ());//byte stream can also be written out without refreshingOut.close (); InputStream in=NewFileInputStream ("C:/file1.txt"); intCh=0;  while((Ch=in.read ())!=-1) {System.out.println (Char) ch);//can be found, if it is in English, can be displayed, but Chinese will be garbled} in.close (); } 
//example, receiving with a byte arrayStatic voidDemo1 ()throwsIOException {InputStream in=NewFileInputStream ("List of c:/. txt"); byte[] buff=New byte[3];//1024x768    intLen=0;  while(Len=in.read (Buff))!=-1) {String str=NewString (buff,0, Len);  System.out.println (str); //It 's garbled .        }}
 //  example available using  static  void  demo2 () throws   ioexception{InputStream in  =new     FileInputStream ("c:/list. txt"  byte  [] buff=new  byte  [In.available ()]; // in.available (), and how many bytes in the current stream are readable      In.read (buff);    System.out.println ( new   String (buff)); In.close ();}  
// example. Copying of pictures Static void Demo3 ()throws  ioexception  {    inputstreamin =new fileinputstream ("C : \\image\\lengtu.jpg ");     byte [] buff=newbyte[In.available ()];    In.read (buff);            OutputStreamout =new fileoutputstream ("e:/tuzi.jpg");    Out.write (buff);    In.close ();    Out.close ();}

Add:

Front, character Stream has wrapper class

BufferedReader, BufferedWriter

Byte stream also has packing class

Bufferedinputstream, Bufferedoutputstream

Iv. conversion Flow InputStreamReader, OutputStreamWriter

Stream byte input to character input streams:

InputStreamReader

public class InputStreamReader extends Reader

Stream the byte output to a character output flow:

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)//create outputstreamwriter using the default character encoding.

OutputStreamWriter (OutputStream out, Charsetencoder enc)//create outputstreamwriter using the given character set.

OutputStreamWriter (OutputStream out, String charsetname)//Create outputstreamwriter using the given character set encoder.

OutputStreamWriter (OutputStream out, String charsetname)//create outputstreamwriter using the specified character set.

 //  example, wrap a transform stream with a buffered stream, convert a stream into a byte stream     InputStream in=new  fileinputstream ("C:/1.txt"  =new      InputStreamReader (in); BufferedReader br  =new   BufferedReader (        Inputreader);    String str  =null  ;  while  ((Str=br.readline ())!=null   
// example reads data from the keyboard, turns it into uppercase print out  Public Static void throws IOException {    bufferedreader br=newnew  InputStreamReader (system.in));    String msg=null;      while ((Msg=br.readline ()) =null) {        System.out.println (msg.touppercase ());}        }

Wu, Bytearrayinputstream and Bytearrayoutputstream

It is used to read and write the contents of the byte array in the form of Io stream, and supports the function of similar memory virtual file or memory image file.

Closing Bytearrayoutputstream is not valid. The 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 ()//without a parameter, a 32-byte buffer is created by default, where the data is written to a byte array. The buffer grows automatically as data is written continuously. Data can be obtained using Tobytearray () and ToString ().

Bytearrayoutstream (int size) creates a buffer based on the specified size

Bytearrayoutstream byte[] Tobytearray () creates a newly allocated byte array. Its size is the current size of this output stream, and the valid contents of the buffer are copied into the array

bytearrayoutputstream byteout=new bytearrayoutputstream ();      Byteout.write ("This is data placed in virtual memory". GetBytes ());                     byte [] bytearray=Byteout.tobytearray ();    String str=new  string (byteArray);    System.out.println (str);    
//Strengthenreads a character from the input stream, then capitalizes the character and writes it to the output stream Public Static voidMain (string[] args)throwsIOException {/*Example 1 uses Bytearrayinputstream and Bytearrayoutputstream bytearrayinputstream in=new bytearrayinputstream ("abcdef". GetB    Ytes ());    Bytearrayoutputstream out=new Bytearrayoutputstream ();                        Transform (in,out);    byte [] Contents=out.tobytearray ();    String Str=new string (contents); System.out.println (str); */                        //Example 2 input and output stream with keyboardtransform (system.in,system.out); //Example 3 using a file input and output streamInputStream in =NewFileInputStream ("C:/1.txt"); OutputStream out=NewFileOutputStream ("E:/big.txt");                    Transform (in,out); }                                Static voidTransform (InputStream in,outputstream out)throwsioexception{intCh=0;  while((Ch=in.read ())!=-1) {out.write (character.touppercase (ch)); }}

Java Foundation--io (ii)

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.