JAVA IO (i) Fundamentals deep Understanding __java

Source: Internet
Author: User

one I/O memory buffer

User space: the region in which the general process is located, the JVM is a regular process, and the code in the zone does not directly access the hardware device

kernel Space: the region in which the operating system resides. The kernel code can communicate with the device controller, control the running state of the user zone process, and so on. Most importantly, all I/O is directly or indirectly through the kernel space

Data Interaction: When a user (Java) process performs I/O operations, it executes a system call that transfers control to the kernel, which is responsible for locating the requested data and transferring the data to the specified buffer in the user's space

kernel space buffers: kernel code reads and writes data to disk I/O operations, because disk I/O operations are slower than direct access to memory several orders of magnitude, so the kernel code will cache the data or read to the kernel space buffer (reduce disk I/O, improve performance)

User space buffers: ibid., the Java I/O process is called by the system to read and write data faster than direct access to the virtual machine memory slow several orders of magnitude, so you can perform a system call, read a large amount of data, the slow presence of virtual machine memory.


two input stream inputstream, output stream OutputStream

The FileInputStream class implements the method of reading a single byte read (), reading a byte array read (byte b[], int off, int len) InputStream. The FileOutputStream class implements a method that writes a outputstream write (int b), writes byte array write (byte b[], int off, int len) (after the face out introduction is skipped, reference in)

		/**
		 *  file output stream constructor
		 *  name path name
		 *  Append parameter is true, data will be added to end of file,
		 *  and existing files with the same name will not be deleted. Otherwise this method deletes all files with the same name
		 *
	    /Public FileOutputStream (String name, Boolean append)
	            throws FileNotFoundException
	        {This
	            (name!= null? New File (name): null, append);
	        }

Because the InputStream implementation class can only read bytes, and every read performs a system call, it is necessary to extend its implementation class, and the filter FilterInputStream inherits from InputStream, is the base class for some extended classes (DataInputStream, Bufferedinputstream).

		public class FilterInputStream extends InputStream {
			protected volatile, inputstream in
			; /**
			 * Constructed method is protected and can only be called (initialized) by subclasses
			 * parameter is the implementation class of InputStream, Example: FileInputStream * *
		    protected FilterInputStream (InputStream in) {
		        this.in = in;
		    }

The read () method initiates a system call at a time, and the cost of the system call is very high, so in order to reduce the number of system calls, it is necessary to bufferedinputstream a read () large number of bytes in the byte array through the adorner. The cache here is not designed to reduce the number of disk IO operations, because the operating system has helped us

		Default cache 8192 byte =8kb, which can be set by parameters
		InputStream in = new Bufferedinputstream (new FileInputStream ("path"), 8192);
		The byte of each write () is cached in a byte array of length 8912 until it is full before the system call is written
		outputstream out = new Bufferedoutputstream (new FileOutputStream ("path"), 8192);
		Same BufferedReader, BufferedWriter.

Data is byte state when read and written, adapter DataInputStream implements Datainput interface can be read bytes, converted to Java basic type in the background and then read, example: Readint reads 4 bytes at a time

	/**
     * DataInputStream class method
	 * Convert to int type, INT4 byte composition, one byte 8 bits
	 * High in front, numeric restore/public
    final int readInt () Throws IOException {
        int ch1 = In.read ();
        int CH2 = In.read ();
        int CH3 = In.read ();
        int CH4 = In.read ();
        if ((ch1 | ch2 | CH3 | CH4) < 0)
            throw new Eofexception ();
        Return ((ch1 <<) + (CH2 <<) + (CH3 << 8) + (CH4 << 0));
    }

DataOutputStream, DataInputStream are commonly used in combination, if the DataOutputStream write data, Java guarantee that we can use datainputstream accurate reading of data. There are also writeUTF () and readUTF () methods that allow you to write and read strings. The data format used to read and write files to these two classes is generally more fixed

		DataInputStream buff = new DataInputStream (new
				               FileInputStream (
				               "path"));

The Read and write methods will block until the byte is read or written out. But usually because the network is busy. Available () method "number of bytes that can be read without blocking", that is, the number of bytes currently readable, so that the following does not block

		For files, this means that the entire file can be read
		int bytesavailable = in.available ();
		if (bytesavailable > 0) {
			byte[] bytes = new Byte[bytesavailable];
			In.read (bytes);
		}

Several methods of InputStream and output stream outputstram of input stream

	public static void Main (string[] args) throws IOException {

		//Bytearrayinputstream can convert a byte array into an input stream
		InputStream in = new Bytearrayinputstream ("Abcdefghi". GetBytes ());
		Determines whether the tag feature is supported
		in.marksupported ();//True
		//Skip 2 bytes
		in.skip (2);
		/**
		 * Mark at current position, not all streams supported (this stream supports) 
		 * If the number of bytes already read from the input stream is greater than 5, this stream allows the tag to be ignored (not supported by this stream)/
		In.mark (5);
		Skips over 2 bytes
		In.skip (2);
		System.out.println ((char) in.read ());//output: E
		//returned to the last token, then read will reread the bytes. If no mark is not reset
		in.reset ();
		System.out.println ((char) in.read ());//output: C
		//More than 5 bytes read
		in.skip (4);
		Mark does not fail
		in.reset ();
		System.out.println ((char) in.read ());//output: C

		byte[] b = new BYTE[10];
		Plug 4 bytes into B, starting with b[5]
		In.read (b, 5, 4);
		Close Flow
		in.close ();

		Outputstram
		OutputStream out = new Bytearrayoutputstream ();
		Scour the output stream, which is to send all buffered data to the destination
		Out.flush ();
		Scour and close the stream
		out.close ();

	}

three-character input stream reader, character output stream writer

the smallest storage unit is byte, regardless of disk or network transmission, so abstract classes InputStream and OutputStream form the basis of the input/output (I/O) class hierarchy.

The underlying output input stream supports only 8-bit byte streams and does not handle 16 Unicode characters Well, since Unicode is used for character internationalization (Java itself char is also 16 Unicode, which contains two bytes), So the adapter InputStreamReader, OutputStreamWriter appears, for the conversion between bytes and characters.

		Bytearrayinputstream can turn a byte array into an input stream
		inputstream in = new Bytearrayinputstream ("Hello". GetBytes ());
		Convert first to character and then cache with BufferedReader
		bufferedreader br = new BufferedReader (new InputStreamReader (in));

Characters are people can read the text (including other national characters), symbols and so on, such as TXT store are characters. Cannot convert to character as Picture MP3

Write data in character format, you can use PrintWriter, and you can set whether to scour the output stream for each write. The Print/println method can write the basic types of characters and Java

	/**
	 * One of the private constructor methods
	 * @param charset converts Unicode characters to bytes for storage
	 * @param file  path * In the selected character encoding
	 @throws FileNotFoundException
	 * *
    private PrintWriter (Charset Charset, file file)
            throws FileNotFoundException
        {This
            is new BufferedWriter (//pair character Cache
            	 new OutputStreamWriter ( 
            	 new FileOutputStream (file), CharSet) ), false);
        

Read data in character format, you can use BufferedReader, and you have a ReadLine () method that reads one row at a time. The data feature is not read by Java basic type. The following is the conversion of bytes to characters in the GBK character set format.

		BufferedReader buff = new BufferedReader (
				              new InputStreamReader (
				              

the Java.util.Scanner class can read data by row or by Java base type.

The Randomaccessfile class can find and write data anywhere in a file, and is suitable for files of known size records. Class has a position that represents the next read or write Byte, and you can set the pointer anywhere in the file by using the Seek () method. It implements the DataOutput, Datainput interface, can read and write to the basic Java type. When using this class, you usually know the layout of the file. And its large versatility can be replaced with NIO.

		Only read access Randomaccessfile in
		= new Randomaccessfile (path, "R");
		Can read, write access
		randomaccessfile inOut = new Randomaccessfile (path, "RW");


four Zipinputstream and Zipoutputstream

	Compression: Write to zip file
	zipoutputstream zipout = new Zipoutputstream (new FileOutputStream ("Compressed file path. zip"));
	Each item in the compressed file is a ZipEntry object
	zipentry entry = new ZipEntry ("file name");
	Add ZipEntry to the compressed file
	zipout.putnextentry (entry);
	Data can be written through the cache stream
	Bufferedoutputstream outbuf = new Bufferedoutputstream (zipout);
	You can also continue nesting
	dataoutputstream dou = new DataOutputStream (OUTBUF);
	
	
	Decompression: Reads the file from the compressed file
	zipinputstream Zipin = new Zipinputstream (new FileInputStream ("Compressed file path. zip"));
	Returns the next ZipEntry object, and no more entries return null
	zipin.getnextentry ();
	Data can be read through the cache stream
	Bufferedinputstream inbuf = new Bufferedinputstream (zipin);
	You can also continue nesting
	datainputstream din = new DataInputStream (INBUF);

Zipinputstream cannot decompress the entire compressed file at once, only one zipentry decompression at a time.

Zipoutputstream cannot compress one folder at a time, only one zipentry at a time.

The Zipinputstream Read method returns 1 at the end of the current zipentry, and then must call Closeentry to read the next zipentry. Same as when writing.


serialization of five objects

Java Object Serialization converts objects that implement the serializable interface into a sequence of bytes and restores the converted byte sequence to the original object, a mechanism that can compensate for differences between different operating systems. Can be serialized on Windows to UNIX recovery

Java Remote method call RMI (remote Mthod invocation) is implemented by serialization, and when remote objects send information, they need to be serialized to transmit parameters and return values

object Serialization is not tight you can save a panorama of an object, track all references contained within an object, and save those objects

when serialized, each object's reference is associated with a serial number, and repeated serialization of the same object is stored as a reference to the object's serial number. Deserialization is the opposite of the process.

When deserializing an object, it compares its serial number with the current serial number of the class to which it belongs, and does not match, indicating that the class has changed after serialization, which involves versioning, which does not outline the

	public static void Main (string[] args) throws IOException, ClassNotFoundException {

		//serialization
		Bytearrayoutputstream out = new Bytearrayoutputstream ();
		Create a ObjectOutputStream write to the specified outputstream
		objectoutputstream oos = new ObjectOutputStream (out);
		This method stores the class of the specified object, the signature of the class, and the value of all non-static and transient (instantaneous)-decorated fields in this class and its superclass
		oos.writeobject ("objects that implement serializable interfaces");
		Oos.writeobject ("Can serialize multiple objects");

		Anti-serialization
		byte[] bs = Out.tobytearray ();
		InputStream is = new Bytearrayinputstream (BS);
		Creates a objectinputstream for reading back object information from the specified InputStream
		objectinputstream ois = new ObjectInputStream (is);
		Returns the class, signature of the object, and the value
		String str1 = (string) ois.readobject ()
		for all non-static and non instantaneous fields in this class and its superclass. String str2 = (string) ois.readobject ();
		System.out.println (str1 + str2);
	}

implements the Externalizable interface, which inherits from Serializable. The Writeexternal method is called when it is serialized, and the object is initialized by invoking the parameterless constructor when deserializing, and then invoking Readexternal.

public class Test implements externalizable {private String str;

	private int i;
	The public Test () {System.out.println ("parameterless constructor") is called when deserializing;
		Public Test (String str, int i) {System.out.println ("constructor");
		This.str = str;
	THIS.I = i;
	@Override public String toString () {return str + i; Called @Override public void writeexternal (ObjectOutput out) throws IOException {Out.writeobject ("Writeexterna
		L ");
	Out.writeint (1); Called @Override public void readexternal (ObjectInput in) throws IOException when deserializing, ClassNotFoundException {This.st
		R = (String) in.readobject ();
	THIS.I = In.readint (); public static void Main (string[] args) throws IOException, ClassNotFoundException {//Initialize test test = new Test ("t
		Est ", 0);
		Serialization of Bytearrayoutputstream OutputStream = new Bytearrayoutputstream ();
		ObjectOutputStream oos = new ObjectOutputStream (outputstream);
		Oos.writeobject (test);
		Oos.close (); Deserialization of Bytearrayinputstream InputStream = new BytEarrayinputstream (Outputstream.tobytearray ());
		ObjectInputStream ois = new ObjectInputStream (InputStream);
		Test TE = (test) ois.readobject ();
		System.out.println (TE);
		Inputstream.close ();

	Ois.close (); }
}

 

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.