Manipulating objects
ObjectInputStream
ObjectOutputStream
The object being manipulated needs to implement serializable (tag interfaces, interfaces that have no methods are often called labeled interfaces)
Saving objects to a hard disk is called persistence of objects.
General situation:
Import Java.io.*;class Person implements serializable{string name;int age; Person (String name, int.) {this.name = Name;this.age = age;} Public String toString () {return name+ ":" +age;}} Class day21{public static void Main (string[] args) throws Exception{//writeobj (); Readobj ();} public static void Writeobj () throws Ioexception{objectoutputstream Oos = new ObjectOutputStream (New FileOutputStream (" Obj.txt ")); Oos.writeobject (New Person (" Lisi "); Oos.close ();} public static void Readobj () throws Exception{objectinputstream Ois = new ObjectInputStream (New FileInputStream ("Obj.txt ")); Person P = (person) ois.readobject (); SOP (P); Ois.close ();} public static void Sop (Object obj) {System.out.println (obj);}}
If changes are made to the original class
Import Java.io.*;class person implements serializable{public static final long Serialversionuid = 42l;//fixed identity for class, easy serialization, The modified class can manipulate an object that has ever been serialized private string name;//at first privatetransient int age;//indicates that age does not want to be serialized static string country = "CN";// Static cannot be serialized by person (string name, int age, String country) {this.name = Name;this.age = Age;this.country = Country;} Public String toString () {return name+ ":" +age+ ":" +country;}} Class Day21{public static void Main (string[] args) throws Exception{//writeobj (); Readobj ();} public static void Writeobj () throws Ioexception{objectoutputstream Oos = new ObjectOutputStream (New FileOutputStream (" Obj.txt ")) Oos.writeobject (New person (" Lisi4 "," SR ")); Oos.close (); public static void Readobj () throws Exception{objectinputstream Ois = new ObjectInputStream (New FileInputStream ("Obj.txt ")); Person P = (person) ois.readobject (); SOP (P); Ois.close ();} public static void Sop (Object obj) {System.out.println (obj);}}
Pipe flow
PipedInputStream
PipedOutputStream
There is a direct connection, one end input, the other output. Use by combining threads.
Import Java.io.*;class Read implements Runnable{private PipedInputStream in; Read (PipedInputStream in) {this.in = in;} public void Run () {try{byte[] buf = new byte[1024]; SYSTEM.OUT.PRINTLN ("No data is blocked before reading"); int len =in.read (BUF); SYSTEM.OUT.PRINTLN ("read data, Block end"); string s = new string (buf, 0, Len); System.out.println (s); In.close ();} catch (IOException e) {throw new RuntimeException ("pipe read failed");}}} Class Write implements Runnable{private PipedOutputStream out; Write (PipedOutputStream out) {this.out = out;} public void Run () {try{system.out.println ("Start writing data, wait 6 seconds"); Thread.Sleep (6000), Out.write ("Pipied lai". getBytes ()); Out.close (); catch (Exception e) {throw new runtimeexception ("Pipe output stream failed");}}} Class Day21{public static void Main (string[] args) throws ioexception{pipedinputstream in = new PipedInputStream (); PipedOutputStream out = new PipedOutputStream (), In.connect (out); Read R = new read (in); Write w = new Write (out), new Thread (R), start (), New Thread (W). Start (); public static void Sop (Object obj) {System.out.prinTLN (obj);}}
Output:
No data is blocked until it is read
Start writing data, wait 6 seconds
Read the data, block the end
Pipied Lai
Randomaccessfile
Supports read and write to random access files.
This class is not a subclass of the IO system, but is inherited directly from object. But it is a member of the IO package. Because it has read and write functions. An array is encapsulated internally and manipulated by pointers to the elements of a group. can be done by
Getfilepointer gets the pointer position and can change the position of the pointer by seek.
In fact, the principle of complete reading and writing is to internally encapsulate the byte input stream and output stream.
As you can see from the constructor, the class can only manipulate files.
And the operation of the file also has a mode: read-only R, read and write RW.
If the mode is read-only R, the file is not created, an existing file is read, and an exception occurs if the file does not exist. If the mode is RW, the action file does not exist, it is created automatically and will not overwrite if it exists.
Can be used for multi-threaded downloads.
Import java.io.*;class day21{public static void Main (string[] args) throws ioexception{writefile_2 (); public static void Writefile_2 () throws Ioexception{randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "RW"); Raf.seek (8 * 3); Raf.write ("Zhou VII". GetBytes ()); Raf.writeint (103); Raf.close ();} public static void ReadFile () throws Ioexception{randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "R");//Adjust the pointer in the object, Before and after can refer to//raf.seek (8);//Skip the specified number of bytes, only the back bar, cannot jump forward raf.skipbytes (8); byte[] buf = new Byte[4];raf.read (BUF); String name = new String (BUF), int age = Raf.readint (), SOP ("Name=" +name+ ". Age= "+age); Raf.close ();} public static void WriteFile () throws Ioexception{randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "RW"); raf.write ("John Doe"); Raf.writeint (getBytes); Raf.write ("Harry". GetBytes ()); Raf.writeint (); Raf.close ();} public static void Sop (Object obj) {System.out.println (obj);}}
DataInputStream
DataOutputStream
A stream object that can be used to manipulate data of the base data type.
Import Java.io.*;class day21{public static void Main (string[] args) throws Ioexception{//writedata ();//readdata ();// Writeutfdemo ();//outputstreamwriter OSW = new OutputStreamWriter (New FileOutputStream ("Utf.txt"), "Utf-8");// Osw.write ("Hello");//osw.close (); Readutfdemo ();} public static void Readutfdemo () throws ioexception{datainputstream dis = new DataInputStream (New FileInputStream (" UtfData.txt ")); String s = Dis.readutf (), SOP (s);d is.close ();} public static void Writeutfdemo () throws Ioexception{dataoutputstream dos = new DataOutputStream (New FileOutputStream (" UtfData.txt "));d Os.writeutf (" Hello "),//utf-8 modified version dos.close (); public static void WriteData () throws Ioexception{dataoutputstream dos = new DataOutputStream (New FileOutputStream (" Data.txt "));d Os.writeint (234);d Os.writeboolean (True);d os.writedouble (92.434);d os.close (); public static void ReadData () throws ioexception{datainputstream dis = new DataInputStream (New FileInputStream ("Data.txt ")); int num = Dis.readint (); Boolean B = Dis.readboolean();d ouble d = dis.readdouble (), sop ("num =" + num), sop ("b =" + B), sop ("D =" + D),;d is.close ();} public static void Sop (Object obj) {System.out.println (obj);}}
The stream object that is used to manipulate the byte array.
Bytearrayinputstream: When constructing, you need to accept the data source, and the data source is a byte array
Bytearrayoutputstream: No data destination is defined at the time of construction. Because a variable-length byte array is already encapsulated inside the object, this is the data destination.
Because both of these stream objects manipulate arrays, system resources are not used. Therefore, close is not done.
In the flow of the operation of the law explained:
SOURCE Device:
Keyboard system.in, hard disk FileStream, memory arraystream.
Purpose Equipment:
Console system.out, hard disk FileStream, memory arraystream.
Manipulate the array with the read and write thoughts of the stream.
Import java.io.*;class day21{public static void Main (string[] args) {//data source Bytearrayinputstream bis = new Bytearrayinputstream ("ABCDEFG". GetBytes ());//Data purpose Bytearrayoutputstream BOS = new Bytearrayoutputstream (); int by = 0; while (by = Bis.read ())! =-1) {bos.write (by);} SOP (Bos.size ()), SOP (Bos.tostring ()),//bos.writeto (New FileOutputStream ("A.txt"));} public static void Sop (Object obj) {System.out.println (obj);}}
Character Stream appears in order to facilitate the manipulation of characters.
More importantly, the code conversion is added.
This is done through the subclass transformation stream.
InputStreamReader
OutputStreamWriter
A character set can be added when two objects are constructed.
Common coding Tables
ASCII: US standard Information Interchange code, denoted by a byte of 7 bits.
Iso8859-1: Latin Code table, European Code table, expressed in 8 bits of a byte.
GB2312: Chinese code table in China
GBK: China's Chinese code table upgrade, incorporating more Chinese character symbols
Unicode: International standard Code, fused with a variety of text. All of the text is represented in two bytes, and the Java language uses Unicode
UTF-8: One word energy saving, with 1 bytes, two bytes can be loaded with two bytes, up to three bytes to represent a character.
Import java.io.*;class day21{public static void Main (string[] args) throws Ioexception{//writetext (); ReadText ();} public static void ReadText () throws Ioexception{inputstreamreader ISR = new InputStreamReader (New FileInputStream (" Gbk.txt ")," UTF-8 "); char[] buf = new Char[10];int len = Isr.read (BUF); String str = new string (buf, 0, Len); SOP (str); Isr.close ();} public static void WriteText () throws Ioexception{outputstreamwriter OSW = new OutputStreamWriter (New FileOutputStream (" Gbk.txt ")," UTF-8 "); Osw.write (" Hello "); Osw.close ();} public static void Sop (Object obj) {System.out.println (obj);}}
Encoding: The string becomes a byte array.
Decode: The byte array becomes a string.
String---->byte[] str.getbytes (); Default GBK encoding Table Str.getbytes (charsetname); Specifying encoding table
byte[]------>string new String (byte[]), Default GBK encoding table, new string (byte[], charsetname), specified encoding table
Import Java.io.*;import java.util.*;class day21{public static void Main (string[] args) throws exception{string s = " Hello "; byte[] B1 = s.getbytes (); SOP (Arrays.tostring (B1));//Output [ -60, -29, -70, -61]b1 = S.getbytes (" GBK "); SOP ( Arrays.tostring (B1));//Output [-60,-29,-70,-61], indicating that GBK is the default encoding table//decoding, encoding and decoding the encoding table to maintain consistent SOP (new String (B1));//Output Hello SOP (New String (B1, "GBK"));//output Hello string str = new String (B1, "iso8859-1"); SOP (str);//Output???? The STR is ISO8859-1 encoded byte[] B2 = str.getbytes ("iso8859-1");//Inside Save [ -60, -29, -70, -61]string s2 = new String (B2, "GBK"); SOP ( s2);//output Hello}public static void sop (Object obj) {System.out.println (obj);}}
Schematic diagram of the above code:
But to change the above iso8859-1 to UTF-8 is not, because UTF-8 and GBK both recognize Chinese, iso8859-1 does not recognize Chinese. Must be careful.
Exercise: There are 5 students, each with 3 courses.
Enter the above data from the keyboard (including the name, the results of each class)
The input format is: zhangsan,30,40,60
Calculates the total score, and stores the student's information and calculated scores in high-low order in the disk file Stuinfo.txt
Steps:
1. Describe the student object.
2. Define a tool class that can manipulate student objects
Thought:
1. By obtaining a row of data entered by the keyboard and taking the data from that row into a student object
2. Because there are many student objects, you need to store them and use them to the collection. Because you want to sort the scores of students, you can use TreeSet.
3. Write the information in the collection to a file.
Import Java.io.*;import Java.util.*;class Student implements comparable<student>{private String name;private int Ma, cn, en;private int sum; Student (String name, int ma, int cn, int en) {this.name = Name;this.ma = ma;this.cn = Cn;this.en = En;sum = Ma + cn + en;} public int CompareTo (Student s) {int num = new Integer (this.sum). CompareTo (New Integer (s.sum)); if (num = = 0) return This.nam E.compareto (s.name); return num;} Public String toString () {return "student[" +name+ "," +ma+ "," +en+ "]";} Public String GetName () {return name;} public int getsum () {return sum;} public int hashcode () {return name.hashcode () + sum * 38;} public boolean equals (Object obj) {if (!) ( obj instanceof Student)) throw new ClassCastException ("Type Mismatch"); Student s = (Student) Obj;return this.name.equals (s.name) && this.sum = = S.sum;}} Class Studentinfotool{public static set<student> Getstudents () throws Ioexception{return getstudents (null);} public static set<student> getstudents (comparator<student> cmp) throws IOexception{bufferedreader bufr = new BufferedReader (new InputStreamReader (system.in)); String line = null; Set<student> stus = null;if (CMP = = null) Stus = new treeset<student> (); elsestus = new Treeset<student> (c (line = Bufr.readline ()) = null) {if (' over '). Equals (line); String[] Info = line.split (","); Student stu = new Student (info[0], Integer.parseint (info[1]), Integer.parseint (Info[2]), Integer.parseint (info[3])); Stus.add (stu);} Bufr.close (); return stus;} public static void WriteToFile (Set<student> stus) throws Ioexception{bufferedwriter BUFW = new BufferedWriter (new FileWriter ("Stuinfo.txt")), for (Student stu:stus) {bufw.write (stu.tostring () + "\ T"), Bufw.write (Stu.getsum () + ""); Bufw.newline (); Bufw.flush ();} Bufw.close ();}} Class Day21{public static void Main (string[] args) throws ioexception{comparator<student> cmp = Collections.reverseorder (); Set<student> stus = studentinfotool.getstudents (CMP); Studentinfotool.writetofile (Stus);}}
The files are written in the following:
Student[wangwu, 34, 343] 427
Student[lisi, 90, 90] 270
Student[zhangsan, 30, 23] 83
[Java Video Note]day21