A simple description of the IO Base's object stream, print flow, standard IO, and scanner classes

Source: Internet
Author: User
Tags serialization string format
Object flow: (serialization and deserialization)
Serialization:
Refers to the Java object data in the heap memory, in some way storing the object in a disk file or passing it to another network node (transmitted over the network). We call this process serialization.
deserialization:The process of restoring object data from a disk file or the object data of a network node to a Java object.

why serialization is needed:
1, in the distributed system, need to share the data JavaBean object, must do the serialization, at this time needs to transfer the object on the network, at this time must transform the object data into binary form.
Objects that are later stored in HttpSession should implement the serialization interface (only the class that implements the serialization interface can do the serialization operation).
2, Service passivation: If the service found some objects for a long time there is no activity, at this time the server will put these memory objects, persisted in the local disk file (Java object--> binary file).
If some objects need to be active, find them in memory first, and then use them. I can't find it. In the disk file, deserialize our object data and revert to the Java object.

The class of the object that needs to be serialized must implement the serialization interface: Java.io.Serializable interface (Flag interface [no abstract method])
The bottom will make a judgment, if the current object is an instance of Serializable, to allow serialization: boolean ret = java object instanceof Serializable;

Most classes in Java already implement the serializable interface.

use object flow to complete serialization and deserialization operations:
ObjectOutputStream: Through the WriteObject method to do serialization operation;
ObjectInputStream: The ReadObject method is used to deserialize the operation.


Prepare a person class:

Import java.io.Serializable;

/**
 * Created by Layne_yao on 2017-7-29 afternoon 4:49:43.
 * csdn:http://blog.csdn.net/jsagacity */public
class person implements Serializable {
	private static Final long serialversionuid = 1L;
	private String name;
	Private String sex;
	Private transient String password;//does not require serialization of
	private int age;

	Public person (string name, string sex, string password, int age) {
		this.name = name;
		This.sex = sex;
		This.password = password;
		This.age = age;
	}

	@Override public
	String toString () {return
		' person [name=] + name + ', sex= + sex +, password= '
				+ PASSW Ord + ", age=" + Age + "]";
	}

Object Stream serialization Operation:

/**
 * Created by Layne_yao on 2017-7-29 afternoon 4:49:25.
 * csdn:http://blog.csdn.net/jsagacity
 *
/public class Objectstreamdemo {public

	static void Main (string[) args) throws Exception {
		file File = new file ("Obj.txt");
		WriteObject (file);
		ReadObject (file);

	Serialization operation
	private static void WriteObject (file file) throws Exception {
		ObjectOutputStream out = new ObjectOutput Stream (New FileOutputStream (
				file));
		Out.writeobject (New Person ("Layne", "Man", "123456");
		Out.close ();
	}

	Deserialization operation
	private static void ReadObject (file file) throws Exception {ObjectInputStream in
		= new Objectinputstr EAM (New FileInputStream (
				file));
		person who = (person) in.readobject ();
		SYSTEM.OUT.PRINTLN (person);
		In.close ();
	}


Run Result:



An object's bytecode object must exist for deserialization operations.

details of serialization, serialized version:
1, if some data do not need to do serialization, such as password, how to do.

In theory, static fields and transient fields cannot be serialized.
Solution: Add a modifier to the field:transient

2, serialized version problem:
The object's class file must be supplied when deserializing the Java object, and the problem is that as the project is upgraded, the system's class file will also be upgraded (Add a field, or delete a field).
This is how to ensure compatibility of two class files.
Java uses Serialversionuid (serialized version number) to determine whether a byte code has changed. If the definition Serialversionuid class variable is not displayed, the value of the class variable is computed by the JVM based on class-related information, and the modified class is calculated differently than before.
Solution: provide a fixed Serialversionuid in the class.

Private static final long serialversionuid = 1L;




Print Flow: Print the data, the print stream can only be the output stream
PrintStream:
byte print stream
PrintWriter: character Print stream
For PrintWriter, when field refreshes are enabled,
PrintWriter pw = new PrintWriter (New Fileoututstream ("File/out"), true);
Call println, or printf, or the format method, and immediately refresh the operation
If automatic refresh is not turned on, it needs to be refreshed manually or automatically refreshed when the buffer is full
With the print stream as the output stream, the output operation is particularly simple because in the print stream:
Print method is provided: printing does not wrap
Provides the Println method: print and wrap
The print and Println methods can support the printout of data of various data types, and remember void println (Object x).

BYTE print stream:

public class Printstreamdemo {public
	static void Main (string[] args) throws Exception {
		PrintStream PS = new Prin Tstream (New File ("File/out.txt"));
		Ps.write ("ABC". GetBytes ());
		Ps.print (false);
		Ps.print ();
		Ps.print ("Layne");
		
		In fact, you can not refresh
		ps.close ();

	}


Character Print stream:

public class Printwriterdemo {public
	static void Main (string[] args) throws Exception {
		PrintWriter PS = new Prin Twriter (New File ("File/out.txt"));
		Ps.write ("ABC");
		Ps.print (false);
		Ps.println ();
		Ps.print ("Layne");
		
		In fact, you can not refresh
		ps.close ();
	}


Formatted output in the print stream (printf method):

System.out.println (); actually equivalent to printstream PS = System.out; Ps.println ();

Java formatted output public
class Printfdemo {public
	static void Main (string[] args) {
		//print a word, Effect: Name: Layne, Age:-
		String name = "Layne";
		int age =;
		Traditional print style
		String str = "Name:" +name+ ", Age:" +age;
		System.out.println (str);
		
		
		Format output
		String format = "Name:%s, Age:%d";
		object[] data = {Name,age}; 
		System.out.printf (format,data);
		System.out.println ();
		Simplified
		System.out.printf ("Name:%s, Age:%d", name,age);

	}


Run Result:




Standard IO:

Standard input: Through the keyboard input data to the program
Standard output: Displaying program data on the screen

There are two constants in the system class:
InputStream in = system.in;
PrintStream out = System.out;

REDIRECT Operation for Standard stream:
Standard input: Through the keyboard input data to the program;
Re-specifies that the source of the input is no longer a keyboard, but a file.
static void Setin (InputStream in), and reassigning the "standard" input stream.
Thereafter, the source of the system.in data is the source specified by the Setin.
Standard output: displaying program data on the screen
The target of the reset output is no longer a screen, but a file.
static void SetOut (PrintStream out), and reassigning the standard output stream.

public class Systemiodemo {public
	static void Main (string[] args) throws Exception {
		//redirect standard input stream
		System.seti N (New FileInputStream ("File/123_copy.txt"));
		REDIRECT standard output stream
		system.setout (new PrintStream ("File/print.txt"));
		
		System.out.println (".....) Start ... ");
		int data = System.in.read (); Reads the first byte
		System.out.println (data) in the file 123_copy.txt; 
		System.out.println (".....) End ... ");
	}





Scanner: scan class, in Java.util package, represents the operation of the input
The existing method: XXX Indicates the data type, such as Byte,int,boolean;
Boolean hasnextxxx ()//To determine whether there is a next type of data
Xxx nextxxx ()///Gets the next data of that type.

public class Scannerdemo {public
	static void Main (string[] args) throws Exception {
		//data in scanned files
		//scanner sc = New Scanner (New File ("File/ch.txt"), "GBK");
		Scan keyboard input data
		//scanner sc = new Scanner (system.in);
		Scan string Data
		Scanner sc = new Scanner ("This is the scan class, I am going to be scanned for data ...") ");
		while (Sc.hasnextline ()) {
			String line = Sc.nextline ();
			System.out.println (line);}}

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.