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

Source: Internet
Author: User
Tags array to string object serialization 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 Program Ape--25. The print stream. Merge streams. 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 the file object, the string path. Byte output stream, 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 self-refresh, do not write the Flush method//inputstreamreader is a byte and character bridge                   PrintWriter pw=new PrintWriter (f,true);//Such a compilation error, PrintWriter class does not have such a constructor/*                   Only PrintWriter (OutputStream Out,boolean autoflush) can be printwriter with true in the constructor function PrintWriter (Writerout, Boolean autoflush) *//PrintWriter pw=new PrintWriter (syst             Em.out);                   PrintWriter pw=new PrintWriter (new FileWriter (f), true);//If you use FileWriter nesting f, you can take a true String s=null; while ((S=bufr.readline ())!=null) {if (S.equals ("OveR "))//Set the 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); }}

—————— Cutting Line ————

/* Split file */import java.io.*;import java.util.*;                    Class ioliou27{public static void Main (string[] args) throws IOException {//qiege ();                     Hebing ();          Hebing2 (); } publicstatic void Qiege ()//* Split file */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 k value is different so there are different associated fragment files Fos.write (by,0,i);                   } fis.close ();                  Fos.close ();              } public static void Hebing ()/* Merge file */throws IOException {Arraylist<filei                    Nputstream> al=new arraylist<fileinputstream> (); Here is the ArrayList set for (int x=1;x<=4;x++) {Al.add (new Fil                               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 who are interviewed 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 ()/* Another merge method */throws IOException {vector<fileinputstr                   Eam> 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 exercises combined with 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); }}

—————— Cutting 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.

Assuming that the members in the class change, the UID will change accordingly.

Of course, you can also voluntarily specify the fixed UID of the class

The approach is to include in the class:

public static final long serializableuid=42l;

When the cited example illustrates the role of the 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 resides and store the object on the hard disk.

At this point Java will give the per class itself to generate the UID, the object generated by the per class is the corresponding

It will have the same UID.

Then delete and change the members of the Per class. The second compilation of the Java file in which the per class resides

The corresponding UID of the resulting. class file will change! The second compilation executes the main function

The Java file in which you are reading the object will report an execution exception. 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 the problem, add in the per class

public static final long serializableuid=42l;

So that no matter how the per class is modified, there is only a corresponding UID number.

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 writes and reads on the hard disk with the same UID number. There will be no exception.

*/

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.                  Thrown 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; }}

—————— Cutting 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); }}

—————— Cutting 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, it is only sufficient for the file talent to operate, the path cannot be manipulated.

The operation file also requires a mode:

Two modes are used frequently: "R" is read-only. "RW" reads and writes.

A large array is also encapsulated in the class. Another pointer indicates an array.

The pointer position is obtained through the Getfilepointer method.

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//assuming that the file does not exist, it will create itself voluntarily                   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 ());//getfilepointer method returns the internal array pointer position//raf.seek (2);//adjust pointers to internal arraysPoint to 2nd position byte[] By=new byte[4]; Raf.read (by);//Read string S=new string (by) according to byte array,//Convert byte array to string int i= raf.readint (                   );//According to the 32-bit read Data soc (s);          Soc (i);                  } public static void Soc (Object obj) {System.out.println (obj);  }}

Dark Horse program Ape--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.