HEADFIRSTJAVA--12_ serialization and file input/output

Source: Internet
Author: User

How to store the state of an object:

1 serialization (if the data is used only by programs that you write yourself)

Creates a file, writes the serialized object to the file, and then reads the serialized object into a file in the program and transforms it into a state;

Note: Reading in a text file is meaningless;

2 Write to a plain text file (if the data needs to be referenced by another program)

Create a text file, with special characters that other programs can parse to write to the file, each line writes the state of an object, separated by commas/tabs;


First, serialization

1 writing serialized objects to a file

A Create FileOutputStream

If the Mygame.ser file does not exist, it is created automatically;

Create a FileOutputStream object that accesses the file;

FileOutputStream filestream = new FileOutputStream ("Mygame.ser");

b creating objectoutputstream for serializing objects

Write the FileStream object, but cannot directly connect to the file, so need parameter guidance;

Serializes the object to a file using the FileOutputStream link objectoutputstream;

ObjectOutputStream OS = new ObjectOutputStream (FILESTREAM);

C Write Object

Serializes and writes the object referenced by the variable to the Mygame.ser file;

Os.writeobject (Characterone); Os.writeobject (charactertwo); Os.writeobject (Characterthree);

D Close ObjectOutputStream

Closes the associated output stream;

Os.close ();

2 data moving in a stream

Connecting a stream to represent the connection of a source to a destination (file or network port);

Generally, a stream is 22 connected, one of which represents a connection, and one is called, because the concatenated stream is usually the underlying; in FileOutputStream, for example, it can write bytes, but we don't usually write bytes, but we write at the object level, so we need a high-level connection stream. ;

FileOutputStream writes a byte to a file, ObjectOutputStream converts the object into a stream-writable data, and when the writeobject of ObjectOutputStream is called, The object is sent to the FileOutputStream to be written in a stream;

Object = Write = "ObjectOutputStream = connect to =" FileOutputStream = = "File

3 objects are serialized

When the object is serialized, the object's primitive master data type variable is serialized, and the instance variable referenced by the object is serialized and all objects referenced by the object's instance variable are serialized;

Class 4 is serialized

If the class is to be serialized, the serializable interface needs to be implemented;

The serializable interface, also the tag of the maker or tag class, is used because there is no method required to implement this interface, and its sole purpose is to declare that the class that implements it is serializable;

If a class is serializable, its subclasses are also automatically serializable, whether or not there is a clear declaration;

Import java.io.*;//No method needs to be implemented, just to be serialized public class Box implements serializable{//the following instance variables will be saved private int width;private int height;public void SetWidth (int w) {width = w;} public void setheight (int h) {height = h;} public static void Main (string[] args) {Box Mybox = new box (); Mybox.setwidth (); Mybox.setheight (20);//May throw an exception try{ FileOutputStream fs = new FileOutputStream ("Mygame.ser"); ObjectOutputStream os = new ObjectOutputStream (fs); O S.writeobject (Mybox); Os.close ();} catch (Exception e) {e.printstacktrace ();}}}

4 serialization is nothing or the whole

The entire object layout must be serialized correctly, otherwise all fails;

Import java.io.*;//Pond object can be serialized public class Pond implements serializable{//has a Duck instance variable private Duck Duck = new Duck ();p Ubli c static void Main (string[] args) {Pond Mypond = new Pond (); Try{fileouputstream fs = new FileOutputStream ("Pond.ser"); objec Toutputstream OS = new ObjectOutputStream (FS),//duck will also be serialized Mypond serialization Os.write (Mypond); Os.close ();} catch (Exception e) {e.printstacktrtace ();}}} Duck cannot be serialized because it does not implement program code that serializes public class duck{//Duck}

If an instance variable cannot or should not be serialized, it is marked as transient (instantaneous), and the serializer skips the instance variable;

If an object is serialized, the reference instance variable of transient is returned as NULL, regardless of the value it was stored at the time;

Import Java.net.*;class Chat implements serializable{//marks the CurrentID variable as a transient String that does not require serialization currentid;// UserName variable will be serialized string username;//more code}

Note: Non-serializable classes can have subclasses that can be serialized;

5 Deserialization: Restoring objects

A Create FileInputStream

If the file does not exist, it will throw an exception;

FileInputStream file = new FileInputStream ("Mygame.ser");

B Create ObjectInputStream

FileStream know how to read, but to rely on the connection stream to provide file access;

ObjectInputStream OS = new ObjectInputStream (fileStream);

C Read Object

Each call to ReadObject () reads the next object from the stream, reading in the same order as the write order and exceeding the number of times it throws an exception;

Object one = Os.readobject (); object one = Os.readobject (); object three = Os.readobject ();

D Convert Object type

ReadObject () Returns a value of type object, so the deserialized object must be converted to its original type;

Gamecharacter elf = (gamecharacter) one; Gamecharacter troll = (gamecharacter); Gamecharacter magician = (gamecharacter) three;

E Close ObjectInputStream

FileInputStream automatically turn off;

Os.close ();

An instance variable of an object is reverted to the state value at the point of serialization, and the transient variable is assigned a null object reference or primitive the default of the primary data type is 0, false equivalent;

Note: Static variables are not serialized, and when the object is restored, the static variable maintains the original look in the class, not the way it was stored;


Ii. input/output of the file

1 writing to a text file

Write text data (strings) similar to writing objects, you can use FileWriter instead of fileoutputstream;

Import Java.io.*;class writeafile{public static void Main (string[] args) {try{//Foo.txt if not present, automatically created FileWriter writer = New FileWriter ("Foo.txt");//string as the parameter Writer.write ("Hello foo!"); Write.close ();} catch (IOException ex) {ex.printstacktrace ();}}}

2 Java.io.File Class

The file class represents the files on the disk, but not the contents of the file;

You can think of the file object as the path to the document, not the file itself, such as file does not read and write files, but can create, browse, delete directory;

2.1 Create a File object representing the existing disk files

File F = new file ("MyCode.txt");

2.2 Creating a new directory

File dir = new file ("Chapter7");d Ir.mkdir ();

2.3 Listing the contents of the directory

if (Dir.isdirectory ()) {string[] dircontents = Dir.list (); for (int i =0; i < dircontents.length; i++) { System.out.println (Dircontents[i]);}}

2.4 Obtaining an absolute path to a file or directory

System.out.println (Dir.getabsolutepath ());

2.5 Delete file or directory (success will return true)

Boolean isDeleted = F.delete ();

3 buffers

Using buffers is more efficient than not using buffers.

Use FileWriter directly, call its write () writing file, but each time will be directly written down, through the BufferedWriter and FileWriter links, BufferedWriter staged a heap of data, until the full time to actually write to the disk, The number of disk operations can be reduced;

If you want to force the buffer to be written immediately, call Writer.flush () to make an illegal request buffer to write down the contents immediately;

Note that you do not need to hold a reference to the FileWriter object here, only bufferedwriterbufferedwriter writer = new BufferedWriter (new FileWriter (Afile));

4 reading a text file

Use the file object to represent the files, to FileReader perform the actual reads, and BufferedReader to make the reads more efficient;

Read is done in a while loop line by row, until the readline () result is null;

Import Java.io.*;class readafile{public static void Main (string[] args) {try{file myFile = new File ("MyText.txt");//FileR Eader is a stream of characters connected to a text file FileReader FileReader = new FileReader (myFile);//FileReader link to bufferedreader for higher efficiency// It will only go back to the disk when the buffer is empty read BufferedReader reader = new BufferedReader (filereader);//Use string variable to take the read obtained result string line = Null;while (line = Reader.readline ()) = null) {//read a row to list a row until there is nothing to read System.out.println (line);} Reader.close ();} catch (Exception e) {e.printstacktrace ();}}}

5 parsing using the split () method of String

In general, we use special characters to divide different elements in the text data;

The split () method of string splits a string into an array of strings by a character/string, where the delimiter is not treated as data;

String totest = "waht is blue + Yellow?/green"; String[] result = Totest.split ("/"); for (String Token:result) {System.out.println (token);}


HEADFIRSTJAVA--12_ serialization and file input/output

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.