JAVA03 IO operation

Source: Internet
Author: User
Tags object serialization

Directory

[TOC]

One, node flow and processing sulfur 1.1 node stream

Also known as low-level flow , can be from or to a specific place (node read and write data)

1.2 Processing Flow

Also known as an advanced stream , data is read and written to an existing connection and encapsulation through the functional invocation of the encapsulated stream.

The construction method of the process flow always takes a parameter with a different stream object. A Stream object passes through multiple wrappers of other streams, becoming a link to the stream.

1.3 Low-level streaming and advanced flow comprehension

Read-write, can have no advanced stream, but must have a low-level stream (the data source is clear)

Ii. input and output stream 2.1 input stream

InputStream is the parent of all byte input streams, and defines the underlying read methods, which are commonly used:

    1. int read ()

      Reads a byte, returned as an int, the "low eight bits" of the int value is valid, and if the return value is-1 means EOF

    2. int read (byte[] D)

      Attempts to read the given data by a length of bytes and into the array, the return value is the actual read to the amount of bytes

2.2 Output stream

OutputStream is the parent class of all byte output streams, which defines the basic writing method, commonly used methods are:

    1. void write (int d)

      Write a byte that writes "Low eight bits" of the given int

    2. void Write (byte[] D)

      Writes out all the bytes in the given byte array

Third, file stream (low-level stream)
 Public classFilestreamdemo {/*** spoke of File stream output usage     * @throws IOException     */     Public Static void FileOutPut()throwsioexception{//No This file will create a file, if it exists, the default will empty the original content, and then output        /** When created, if the second parameter is specified and the value is true, the content written out through the FOS is appended to the end of the file         *          * */FileOutputStream fos =NewFileOutputStream ("Fos.txt",true); String str ="I'm pudgy.";//String converted to bytes, specified as Utf-8        byte[] data = str.getBytes("Utf-8"); Fos.Write(data); Fos.Close(); }/*** spoke of File stream input usage     * @throws IOException     */     Public Static void FileInput()throwsioexception{FileInputStream Fistream =NewFileInputStream ("Fos.txt");byte[] data =New byte[ -];intLen = Fistream.Read(data); String str =NewString (data,0Len"Utf-8"); System. out.println(str); } Public Static void Main(string[] args)throwsIOException {//FileOutPut ();        FileInput(); }}
Iv. buffered streams (Advanced streaming)
/*** This class is mainly about the use of buffer streams* Buffer Stream In fact, the internal definition of a buffer array (buffer pool of a certain size) to improve read and write efficiency, slow hard disk IO, into the cache of data read * @authorGupan * */ Public classCachestreamdemo { Public Static void Main(string[] args)throwsIOException {FileInputStream Fistream =NewFileInputStream ("Fos.txt");//Add cache stream to FistreamBufferedinputstream bis =NewBufferedinputstream (Fistream); FileOutputStream Fostream =NewFileOutputStream ("Fos.txt");//Add cache stream to FostreamBufferedoutputstream BOS =NewBufferedoutputstream (Fostream);intD =-1; while(d = bis.Read()) != -1) {Bos.Write(d); } System. out.println("Copy Complete");//When the buffer is not full, force the buffer to be brushed to the hard disk .Bos.Flush();//Close the Advanced stream, which closes both the advanced and low-level streams that are encapsulatedBis.Close(); Bos.Close(); }}
V. Object Stream 5.1 Serialization of objects

The process of converting an object to a set of bytes

5.2 Persistence of objects

Writes the bytes of the object to the hard disk for long-term preservation

5.3 Deserialization
/*** This class is mainly about the use of object flow* Object flow is useful for reading and writing objects in Java * * Object output stream:* The given object can be converted to a set of bytes after writing out* Object input stream: *       *  * @authorGupan * *///For an object, if you want to use object flow, store object instance, need implement serializable interface, this is an abstract interface, there is no interface method,//But at compile time, the compiler will recognize which classes implement this interface and do some of the underlying things, such as the Serializable interface, also called the signature interface ./* *  ** After implementing the Serializable interface, you need to add a version number Serialversionuid, or there will be a warning. If you do not write Serialversionuid, the system defaults to a more class-like interface to generate a version number* (This version number will vary with the structure of the class, but in the case of class structure change, because of the serialization and deserialization version number is different, the deserialization will be error, the custom version number can avoid the above situation,* When the version number is the same, but the structure of the class changes, the changed attribute removal disappears, the new property takes the default value) * */ Public classObjectstreamdemoImplementsserializable{/**     *      */    Private Static Final LongSerialversionuid = 1L;PrivateString name;Private intAgePrivateString gender;//When a class uses the Serializable interface, a keyword can be implemented transient    //When an instance of a class is serialized, the attribute with the Transient keyword is not serialized when serialized, meaning that the storage object is thin    PrivateList <String> Otherinfo; Public Objectstreamdemo() {    } Public Objectstreamdemo(String name,intAge, String gender,list <String> otherinfo) { This.name= name; This. Age= age; This.Gender= gender; This.Otherinfo= Otherinfo; }@Override     PublicStringtoString() {//TODO auto-generated method stub        return  This.name+","+ This. Age+","+ This.Gender+","+ This.Otherinfo; } PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age= age; } PublicStringGetgender() {returnGender } Public void Setgender(String gender) { This.Gender= gender; } PublicList<string>Getotherinfo() {returnOtherinfo; } Public void Setotherinfo(list<string> otherinfo) { This.Otherinfo= Otherinfo; } Public Static void Main(string[] args)throwsIOException, classnotfoundexception {Objectstreamdemo p =New Objectstreamdemo(); P.SetName("Pudgy"); P.Setage( -); P.Setgender("Male"); List <String> Otherinfo =NewArraylist<string> (); Otherinfo.Add("is a student"); Otherinfo.Add("2018 Graduation"); P.Setotherinfo(Otherinfo);//************************************************* object serialization *************************************************FileOutputStream fos =NewFileOutputStream ("Info.txt");//Using object FlowObjectOutputStream Oos =NewObjectOutputStream (FOS);//Persistence of objectsOos.writeobject(p); Oos.Flush(); Oos.Close();//************************************************* object deserialization *************************************************FileInputStream Fistream =NewFileInputStream ("Info.txt"); ObjectInputStream Ois =NewObjectInputStream (Fistream); Objectstreamdemo pRe = (Objectstreamdemo) ois.ReadObject(); System. out.println(pRe); Ois.Close(); }}
Vi. Reader and writer

The top-level parent of the character input stream and the character output stream, which is a character stream that reads and writes data. Process one Unicode at a time. The bottom of the character stream is still the basic byte stream, and all the character streams are advanced streams

Common methods of 6.1 reader
    1. int read ()

      Reads a character that returns an int value of "low 16" bit valid

    2. int read (char[] CHS)

      The length of a character array is read from the stream and stored in the array, and the return value is the actual number of characters read to

      Common methods of 6.2 writer
    3. void write (int c)

      Writes out a character that writes out the character represented by the "low 16-bit" given int value

    4. void write (char [] CHS)

      Writes out all the characters in the given character array

    5. void write (String str)

      Writes the given string out

    6. void Write (char[] CHS, int offset, int len)

      Writes the given array of characters from the offset out of the beginning of the continuous Len-chromium character

6.3 Commonly used reader and Writer6.3.1 InputStreamReader and OutputStreamWriter

The conversion of the character flow to the byte stream is completed , and the other character streams can be processed after the conversion of these two character streams.

  1. InputStreamReader

    Represents the character input stream, which converts byte data to characters and reads from the stream according to the specified character set.

  2. OutputStreamWriter

    Represents the character output stream, which can be used to set the character set and to convert the character to the corresponding byte following the specified character set, using the stream to write out

     Public classReaderandwriterdemo { Public Static void Main(string[] args)throwsIOException {FileOutputStream fos =NewFileOutputStream ("Osw.txt"); OutputStreamWriter OSW =NewOutputStreamWriter (FOS,"Utf-8"); Osw.Write("Pudgy is rolling forward."); Osw.Close(); FileInputStream FIS =NewFileInputStream ("Osw.txt"); InputStreamReader ISR =NewInputStreamReader (FIS,"Utf-8");intD =-1; while((d = ISR.)Read()) != -1) {System. out.Print((Char) d); }}}
6.3.2 BufferedWriter and BufferedReader

Characteristics

Read and write strings by line

6.3.3 PrintWriter
    1. PrintWriter

      With the automatic row refresh buffer character output stream, when created, he will certainly create bufferedwriter in memory as a buffer function overlay
      "' Java
      /**

    • This class mainly speaks of the use of buffer character streams.
    • @author Think
    • */
      public class Printwriterdemo {
      public static void Main (string[] args) throws FileNotFoundException, Unsupportedencodingexception {
      Internally helped us create the file object
      PrintWriter pw = new PrintWriter ("Pw.txt", "utf-8");

      pw.println("圆滚滚在向前滚");pw.println("滚得越来越远了");pw.close();FileOutputStream fos = new FileOutputStream("pw.txt", true);// 构造方法内部有创建字符流,但是这种方式不能指定字符集,如果要指定字符集,那么指定一// 个OutputStreamWriter对象,创建时指定字符集pw = new PrintWriter(fos);pw.println("滚得又远了一点");pw.close();

      }
      }
      ```

JAVA03 IO operation

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.