Java Foundation-io Stream (ii)

Source: Internet
Author: User
Tags serialization throw exception

One, the byte stream

The byte stream is read and written through bytes, and his use of the object is more extensive than the character stream. This is mainly because they read and write files
Decision-making. A character stream reads and writes a file by converting the bytes read to a character through the default encoding table, converting the characters to byte storage through the default encoding table
To the file, while improving the reading and writing efficiency of the text document in the process, this operation of converting bytes into characters when facing a non-text file is
The reason for the Code table may cause the loss of bytes, causing the file to be missing. So use a byte stream when working with non-text documents.

Second, InputStream class

This abstract class is a superclass (read) of all classes of the byte input stream, and its common subclasses are FileInputStream, ObjectInputStream.
The common methods of this kind are similar to the reader class, and their common methods are:
(1) Closes this input stream and frees all system resources associated with the stream, close ()

(2) reading the next byte of data from the input stream, read ()

(3) reads a certain number of bytes from the input stream and stores it in buffer array B, read (byte[] b)

(4) reads up to Len data bytes in the input stream into a byte array, read (byte[] b, int off, int len)

1, FileInputStream class

The FileInputStream class is a common implementation class for InputStream abstract classes that can be used to read non-text files such as video, audio, pictures, or
Reading a text file (the FileReader class is recommended for reading text files), and its construction method is similar to FileReader, where the path name or file object can be passed as
Parameters. It inherits all the methods of the InputStream class.

2, ObjectInputStream class

The ObjectInputStream class is primarily used for reading objects, inheriting all methods of the InputStream class. His method of construction is:
(1) Create a ObjectInputStream read from the specified InputStream

ObjectInputStream (InputStream in)

Because of its nature of reading objects, he has his own unique approach:
(1) Reading objects from ObjectInputStream, ReadObject ()

Examples of two kinds of traversal methods:

1 //Throw Exception2 Private Static voidMETHOD2 ()throwsIOException, FileNotFoundException, classnotfoundexception {3 //Create ObjectInputStream objects based on the FileInputStream object passed in4ObjectInputStream Ois =NewObjectInputStream (NewFileInputStream ("Aa.txt"));5 //traverse file until no file is readable, catch thrown exception, end loop6 Try {7  while(true) {8 //Read File9Object ReadObject =Ois.readobject ();Ten System.out.println (readobject); One } A //catching an abnormal end loop -}Catch(eofexception e) { -SYSTEM.OUT.PRINTLN ("Output is complete"); the //must be executed, typically to close the stream -}finally { - //Close Resource - ois.close (); + } -}

To pass an object into the collection, write the collection to a file, read the collection

1  Public Static voidMain (string[] args)throwsException, IOException {2 //method ();3 //method2 ();4 //Create student Objects5Student Student =NewStudent ("Zhang San", 18);6Student Student2 =NewStudent ("Baijie", 19);7Student Student3 =NewStudent ("Zhao Si", 39);8 //Create a collection9arraylist<student> lists =NewArraylist<>();Ten //throw students into the collection One Lists.add (student); A Lists.add (student2); - Lists.add (STUDENT3); - //Create ObjectOutputStream objects based on the FileOutputStream object passed in theObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ("Bb.txt")); - //writes a collection to - oos.writeobject (lists); -ObjectInputStream Ois =NewObjectInputStream (NewFileInputStream ("Bb.txt")); + //reading a collection from a file -Object ReadObject =Ois.readobject (); + //Down Transformation Aarraylist<student> re = (arraylist<student>) ReadObject; at //iterating through the collection -  for(Student student4:re) { - System.out.println (STUDENT4); - } - //Close Resource - ois.close (); inOos.close ();

Third, OutputStream class

This abstract class is a superclass (write) of all classes that represent the output byte stream, and its common subclasses are FileInputStream, ObjectInputStream.
Common methods of this class are similar to reader classes, and their common implementation classes are:
(1) FileOutputStream class

(2) ObjectOutputStream class
The common methods of this kind are similar to the writer class, and the common methods are:
(1) Close this output stream and release all system resources related to this stream, close ()

(2) flush this output stream and force write out all buffered output bytes, flush ()

(3) writes Len bytes from offset off in the specified byte array to this output stream, write (byte[] b, int off, int len)

1, FileOutputStream class

The FileOutputStream class is a common implementation class for the OutputStream abstract class, which is constructed in a similar way to FileWriter, which can pass the path name or
The file object is a parameter. It inherits all the methods of the OutputStream class.

Example of copying a file with a character stream:

1 //Create a File object2File File =NewFile ("D:\\songs\\ Little Apple mp4");3 //Create a FileInputStream object from file4FileInputStream fi=Newfileinputstream (file);5 //define int to store array length6 inti;7 //defining a byte array8 byte[] b=New byte[1024];9 //creates a FileOutputStream object based on a given pathTenFileOutputStream fo=NewFileOutputStream ("d:\\aa\\ Little Apple mp4"); One //Loop Read A  while((I=fi.read (b))!=-1) { - //Write File -Fo.write (b, 0, i); the } - //Close Resource - fo.close (); -Fi.close ();

2, ObjectOutputStream class

You can use the ObjectOutputStream class to write objects to a file, note that the class of the object being written to be serialized, otherwise you are
The exception is reported when modified.
Examples of serialization of classes:

1 classStudentImplementsSerializable {2 /**3 * Serial number if the system is not generated automatically generated, but you change the class member variable sequence number will also change, will be error so to rewrite4 */5 //implementing the Serializable interface for serialization6 Private Static Final LongSerialversionuid = 4123259833120003092L;7 PrivateString name;8 Private intAge ;9 Ten  PublicStudent () { One Super(); A //TODO auto-generated Constructor stub - } -  the  PublicStudent (String name,intAge ) { - Super(); -  This. Name =name; -  This. Age =Age ; + } -  + @Override A  PublicString toString () { at return"Student [name=" + name + ", age=" + Age + "]"; - } -}

Examples of writing objects:

1 //Create a ObjectOutputStream object2ObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ("Aa.txt"));3 //Create student Class4Student Student =NewStudent ("Zhang San", 18);5Student Student2 =NewStudent ("Baijie", 19);6 //Write Data7 Oos.writeobject (student);8 Oos.writeobject (student2);9 //Close ResourceTenOos.close ();

Iv. use of the conversion stream

The conversion stream is not a subclass of the byte stream, but a subclass of writer and reader, because it involves the conversion of the byte stream and the character stream, so say it here.

1, InputStreamReader (character input stream)

The character input stream is a bridge of bytes flowing to a character stream. It can convert a section character stream object into a character stream object because it is input, so the byte data is transferred
Change to character data. Its common construction method is: InputStreamReader (InputStream in).

2, OutputStreamWriter (character output stream)

He is a bridge of character flow to the word stream. It can convert a byte stream object into a character stream object, because it is output, so character data is converted to bytes
Data. Its common construction method is to create a-outputstreamwriter (OutputStream out) using the default character encoding.

Example:

1  Public Static voidMain (string[] args)throwsIOException {2 //standard input Stream3InputStream in =system.in;4 //Convert Stream5InputStreamReader InputStreamReader =NewInputStreamReader (in);6 //Create a FileWriter object7FileWriter FW =NewFileWriter ("A.txt");8 //Storage Array Length9 inti;Ten Char[] C =New Char[1024]; One //Loop Read A  while((i = Inputstreamreader.read (c))! =-1) { - //writes an array to the specified file, written from 0 to I, to prevent duplicate data from appearing -Fw.write (c, 0, i); the //Brushes - Fw.flush (); -  - } + //Close Resource - fw.close (); + inputstreamreader.close (); A }  at}

Java Foundation-io Stream (ii)

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.