Dark Horse programmer--25, print stream, merge stream, object serialization, pipeline flow, Randomaccessfile

Source: Internet
Author: User
Tags array to string object serialization

------<ahref= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

Dark Horse programmer--25, print stream, merge stream, object serialization, pipeline flow, Randomaccessfile

/*

Io stream Print stream: A stream dedicated to printing

BYTE print stream PrintStream

The PrintStream constructor can receive the file object, string path, byte output stream

Character Print stream PrintWriter

The PrintWriter constructor can receive a file object, a string path, a byte output stream, a character output stream

PrintWriter has a Refresh method. Remember to refresh when you write.

*/

Import java.io.*;class ioliou25{public static void Main (string[] args) throws IOException {                   File F=new file ("F:\\yyyyyyyk.txt");         BufferedReader bufr=new BufferedReader (New InputStreamReader (system.in));                   PrintWriter pw=new PrintWriter (system.out,true);//This with true automatically refreshes without writing the Flush method//inputstreamreader is a byte-to-character bridge                   PrintWriter pw=new PrintWriter (f,true);//This compilation error, PrintWriter class does not have this constructor/*                   The PrintWriter constructor can take true only PrintWriter (OutputStream Out,boolean AutoFlush) PrintWriter (Writerout, Boolean autoflush) *//PrintWriter pw=new PrintWriter (System.ou             T);                   PrintWriter pw=new PrintWriter (new FileWriter (f), true);//use FileWriter to nest F with a true String s=null; while ((S=bufr.readline ())!=null) {if (S.equals ("over"))//set closing sentence break; Pw.write (S.touppercase ()); There is no line break pw.println (S.touppercase ());//This is more common with println methods//pw.flush (                   );                   } bufr.close ();          Pw.close ();                    } public static void Soc (Object obj) {System.out.println (obj); }}

—————— Split Line ————

/* Cut files */import java.io.*;import java.util.*;                    Class ioliou27{public static void Main (string[] args) throws IOException {//qiege ();                     Hebing ();          Hebing2 (); } publicstatic void Qiege ()/* Cut files */throws ioexception {file F=new file ("f:\\8.11\ \8.11 practice. png ");//Create File Object FileInputStream fis=new FileInputStream (f);//Associated Purpose file Fileou                   Tputstream Fos=null;                   int i=0,k=0;                   Byte[] By=new byte[1024*10];                          while ((I=fis.read (by))!=-1) {k++;                               Fos=new FileOutputStream ("f:\\8.11\\8.11 Exercise" +k+ ". part");                                                   Each cycle has a different k value, so there should be a different associated fragment file Fos.write (by,0,i);                   } fis.close ();                  Fos.close ();              } public static void Hebing ()/* Merge file */throws IOException {Arraylist<filei                    Nputstream> al=new arraylist<fileinputstream> (); The ArrayList set for (int x=1;x<=4;x++) {al.add (new Fil) is used here.                               Einputstream ("f:\\8.11\\8.11 Exercise" +x+ ". part"));                   The stream associated with the file is loaded into the collection} final iterator<fileinputstream> it= al.iterator (); Local members that are accessed by anonymous internal classes are final decorated enumeration<fileinputstream> en=new enumeration<                       Fileinputstream> () {public boolean hasmoreelements () {                    return It.hasnext ();                    } public FileInputStream Nextelement () {return it.next ();                                 }    };                   Sequenceinputstream sis=new sequenceinputstream (en);                   FileOutputStream fos=new FileOutputStream ("f:\\8.11\\8.11 practice merging. png");                   int i=0;                   Byte[] by= new byte[1024];                        while ((I=sis.read (by))!=-1) {fos.write (by,0,i);                   } sis.close ();                   Fos.close (); } public static void Hebing2 ()/* The second method of merging */throws IOException {vector<fileinputstre                   Am> v=new vector<fileinputstream> (); for (int x=1;x<=4;x++) {V.add (New FileInputStream ("f:\\8.11\\8.11 Exercise" +x+ ". Par                    T "));             } enumeration<fileinputstream> en=v.elements ();                   Sequenceinputstream sis=new sequenceinputstream (en); FileOutputStream fos=new FileOutputStream ("F:\\8.11\\8.11 Practice merging 2.png");                   int i=0;                   Byte[] By=new byte[1024*10];                      while ((I=sis.read (by))!=-1) {fos.write (by,0,i);                   } sis.close ();                              Fos.close ();                 } public static void Soc (Object obj) {System.out.println (obj); }}

—————— Split Line ——————

/*

Serialization of objects

Use of ObjectInputStream and ObjectOutputStream.

Serialization is the storage of objects on the hard disk.

*/

/*

Implements the serializable interface, the class is identified with a UID number.

The UID number is related to the member.

If the members in the class change, the UID changes accordingly.

Of course, you can automatically specify a fixed UID for this class

The way to do this is to add the following in the class:

public static final long serializableuid=42l;

One example illustrates the role of UID:

The first time you compile the. class file generated by the Java file where the per class resides,

Then compile the Java file where the main function is running and store the object on the hard disk.

At this point, Java will automatically generate a UID for the per class, and the object generated by the per class is the corresponding

It will have the same UID.

Then delete and change the member of the class, the second compile the Java file where the per class

The UID corresponding to the resulting. class file will change! Second compilation run main function

A running exception is reported when the Java file in which it is located needs to read the object. Because

The UID number of the object that is already stored in the hard disk is the UID number of the first time, where the per class

The UID number of the. class file produced by the second Java file is different from the UID number of the object, so

There will be an exception.

In order to solve this problem, add in the per class

public static final long serializableuid=42l;

So that no matter how the per class is changed, only one UID number is corresponding.

The object UID number of the per class is also this, which is the UID number of the. class file generated by the Per-class compilation.

The object is written and read on the hard disk with the same UID number, and no exception occurs.

*/

Import Java.io.*;import java.util.*;            Class ioliou28{public static void Main (string[] args) throws Exception {//Xieru ();         Duqu ();                   public static void Xieru () throws Exception {file F=new file ("f:\\ North. txt");                   FileOutputStream fos=new FileOutputStream (f);                   ObjectOutputStream oops=new ObjectOutputStream (FOS);                   Oops.writeobject (New Per ("Hoo hoo", "JKL"));                                         To write to the object, the class to which the object is written must be implemented with the serializable pretext oops.close ();                     public static void Duqu () throws Exception {file F=new file ("f:\\ North. txt");                    FileInputStream fos=new FileInputStream (f);                    ObjectInputStream oips=new ObjectInputStream (FOS); Object Obj=oips.readobject (); The//readobject method returns objects of type//readobject method throwsOut a classnotfoundexception, for simplicity, throws are exception Per P = (per) obj;                       Oips.close ();                                  Soc (p);                     } public static void Soc (Object obj) {System.out.println (obj); }}import java.io.*;import Java.util.*;class Per implements serializable{//public static final long serializableuid=4    2L;         The static String name= "nameless";//static member cannot be serialized as private int age;               Transient string country= "cn";//transient decorated members cannot be serialized Per (string name, int age,string country) {                    This.name=name;                    This.age=age;         This.country=country;                    } public String toString () {return name+ ":" +age+ ":" +country; }}

—————— Split Line ——————

/*

Pipe Flow:

PipedInputStream PipedOutputStream

Pipeline inflow and pipeline output flow can be connected, and multithreading is closely related.

Typically a thread is responsible for the pipeline input stream, and one thread is responsible for the pipeline output stream.

*/

Class Read () implements Runnable throws ioexception{private PipedInputStream pis=null;              Read (PipedInputStream PiS) {This.pis=pis;                      } public void Run () {int i=0;                      Byte[] By=new byte[1024];           while ((I=pis.read (by))!=-1) {//fill in the contents}         }}class Write () implements Runnable throws ioexception{private PipedOutputStream pos=null;             Write (PipedOutputStream pos) {this.pos=pos;                      } public void Run () {//int i=0;                            Byte[] By=new byte[1024];           Pos.write ("Huhuhu". GetBytes ());         }}import java.io.*;class ioliou29{public static void Main (string[] args) throws IOException {PipedinputstreAm Pis=new PipedInputStream ();                   PipedOutputStream pos=new PipedOutputStream ();                   Pis.connect (POS);//pipeline input and pipeline output stream connection read r=new read (PiS);                   Write W=new write (POS);                   Thread t1=new thread (r);                    Thread T2=new thread (w);                    T1.start ();         T2.start ();                           } public static void Soc (Object obj) {System.out.println (obj); }}

—————— Split Line ——————

/*

The Randomaccessfile class is a member of the IO package

Random access, this kind of application is very wide,

It encapsulates the byte write stream and the byte read stream,

So it has the function of reading and writing,

However, only the file can be manipulated, and the path cannot be manipulated.

The operation file also requires a pattern:

Two commonly used modes: "R" read-only, "RW" Read and write.

The class also encapsulates a very large array, and a pointer indicates an array.

Using the Getfilepointer method to get the pointer position,

Specifying the pointer position by the Seek method

*/

Import Java.io.*;class ioliou30{publicstatic void Main (string[] args) throws IOException {writ          E ();               Read ();                   public static void Write () throws IOException {file F=new file ("f:\\ learning. txt");                   Randomaccessfile Raf=new Randomaccessfile (F, "RW");//Associate the file and determine the operating mode//If the file does not exist, it will be created automatically                   Raf.write ("123". GetBytes ());                   Raf.writeint (56);//write a number preferably with Writeint, write in 32-bit form raf.write ("456". GetBytes ()); Raf.writeint (85);//writing a number preferably with Writeint, in 32-bit form} public static void Read () throw                   s IOException {file F=new file ("f:\\ learning. txt"); Randomaccessfile Raf=new Randomaccessfile (F, "RW");//Associate the file and determine the operating mode Soc ("raf.getfilepointer () =" +raf.getfi Lepointer ()); The//getfilepointer method returns the internal array pointer position//raf.seek (2);//Adjusts the pointer of the internal array to point to2nd place byte[] By=new byte[4]; Raf.read (by);//Read string S=new string (by) in byte array,//Convert byte array to string int i= raf.readint (                   );//Read Data SOC (s) according to 32 bits;          Soc (i);                  } public static void Soc (Object obj) {System.out.println (obj);  }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse programmer--25, print stream, merge stream, object serialization, pipeline flow, Randomaccessfile

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.