Java I/O stream

Source: Internet
Author: User
Tags file copy object serialization

The Java.io.File class is used to represent files (directories)
The file class is used only for information (name, size, etc.) that represent files (directories) and cannot be used for access to file content

Randomaccessfile Java provides access to the contents of a file that can be read or written.
Randomaccessfile supports random access to files and can access any location in the file

(1) Java file model
The file on the hard disk is stored in byte byte byte and is a collection of data
(2) Open file
There are two modes of "RW" (read-write) "R" (read-only)
Randomaccessfile RAF = new Randomeaccessfile (file, "RW")
The file pointer opens the file when the pointer is at the beginning pointer = 0;
(3) How to write
Raf.write (int)---> Write only one byte (last 8 bits), while the pointer points to the next position, ready to write again
(4) Method of Reading
int b = raf.read ()---> read one byte
(5) The file must be closed after reading and writing (Oracle official note)


Serialization and basic type Serialization
1) The process of converting type int to 4byte or converting other data types to byte is called serialization
Data---->n byte
2) deserialization
Converting n byte to one data
Nbyte---> Data
3) Randomaccessfile provides a basic type of read-write method that can
serialize the basic type data to a file or deserialize the contents of a file into a data
IO stream (input stream, output stream)
Byte stream, Character streams
1. Byte stream
1) inputstream, OutputStream
InputStream Abstract How the application reads data
OutputStream Abstracts How the application writes data
2) EOF = end read to 1 reading to the end
3) input stream basic method
Int b = In.read (); reads a byte unsigned fill to int low eight bits. -1 is EOF
In.read (byte[] buf)
In.read (byte[) Buf,int start,int size)
4) Output stream Basic method
Out.write (int b) writes out a byte-to-stream, B's low 8-bit
Out.write (byte[] buf) to write the BUF byte array to the stream
Out.write (byte[] buf,int start,int size)

5) FileInputStream---> Specifically read data on File
6) FileOutputStream Implements the method of writing a byte data to a file
7) Dataoutputstream/datainputstream
extends the "stream" function to read Int,long, characters, and other types of data
DataOutputStream
Writeint ()/writedouble ()/writeutf ()

8) Bufferedinputstream&bufferedoutputstream
These two stream class bit IO provide operations with buffers that typically open files for writing
Or read operation, the buffer is added, which improves the performance of the IO
Putting input into a file from an application is equivalent to pouring a cylinder of water into another cylinder:
FileOutputStream--->write () method is equivalent to "transfer" the water one drop at a time.
The Dataoutputstream-->writexxx () method will be convenient, equivalent to a scoop of water "transfer" the past
Bufferedoutputstream--->write method is more convenient, the equivalent of a float a scoop first into the bucket, and then poured from the barrel into another cylinder, performance improved

 PackageCom.imooc.io;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException; Public classIoutil {/*** Read the contents of the specified file, output to the console according to 16 input * and 10 bytes per output *@paramfileName * Single byte read not suitable for large files, large file efficiency is very low*/     Public Static voidPrinthex (String fileName)throwsioexception{//read the file as a byte streamFileInputStream in =NewFileInputStream (fileName); intb; inti = 1;  while((b = in.read ())!=-1){            if(b <= 0xf){                //number of units front complement 0System.out.print ("0"); } System.out.print (integer.tohexstring (b)+"  "); if(i++%10==0) {System.out.println ();    }} in.close (); }    /*** Bulk Reading, high efficiency for large files, is also the most common way to read files *@paramFileName *@throwsIOException*/     Public Static voidPrinthexbybytearray (String fileName)throwsioexception{FileInputStream in=NewFileInputStream (fileName); byte[] buf =New byte[8 * 1024]; /*Bulk Read bytes from in, put into buf this byte array, * starting from the No. 0 position, up to Buf.length * Returns the number of bytes read*/        /*int bytes = In.read (buf,0,buf.length);//Read all at once, indicating that the byte array is large enough int j = 1;            for (int i = 0; i < bytes;i++) {System.out.print (integer.tohexstring (Buf[i] & 0xff) + "");            if (j++%10==0) {System.out.println (); }        }*/      intbytes = 0; intj = 1;  while((bytes = In.read (buf,0,buf.length))!=-1){           for(inti = 0; I < bytes;i++) {System.out.print (integer.tohexstring (buf[i)& 0xff) + ""); if(j++%10==0) {System.out.println ();    }}} in.close (); }    /*** file copy, byte bulk read *@paramSrcfile *@paramDestFile *@throwsIOException*/     Public Static voidCopyFile (File srcfile,file destfile)throwsioexception{if(!srcfile.exists ()) {            Throw NewIllegalArgumentException ("File:" +srcfile+ "does not exist"); }        if(!Srcfile.isfile ()) {            Throw NewIllegalArgumentException (srcfile+ "Not a file"); } FileInputStream in=NewFileInputStream (srcfile); FileOutputStream out=NewFileOutputStream (destfile); byte[] buf =New byte[8*1024]; intb;  while((b = In.read (buf,0,buf.length))!=-1) {out.write (buf,0, B); Out.flush ();//Better Add} in.close ();            Out.close (); }    /*** Make a copy of the file, using buffered byte stream *@paramSrcfile *@paramDestFile *@throwsIOException*/     Public Static voidCopyfilebybuffer (File srcfile,file destfile)throwsioexception{if(!srcfile.exists ()) {            Throw NewIllegalArgumentException ("File:" +srcfile+ "does not exist"); }        if(!Srcfile.isfile ()) {            Throw NewIllegalArgumentException (srcfile+ "Not a file"); } Bufferedinputstream bis=NewBufferedinputstream (NewFileInputStream (srcfile)); Bufferedoutputstream Bos=NewBufferedoutputstream (NewFileOutputStream (destfile)); intC;  while((c = bis.read ())!=-1) {bos.write (c); Bos.flush ();//Flush Buffers} bis.close ();    Bos.close (); }    /*** Single byte, no buffer for file copy *@paramSrcfile *@paramDestFile *@throwsIOException*/     Public Static voidCopyfilebybyte (File srcfile,file destfile)throwsioexception{if(!srcfile.exists ()) {            Throw NewIllegalArgumentException ("File:" +srcfile+ "does not exist"); }        if(!Srcfile.isfile ()) {            Throw NewIllegalArgumentException (srcfile+ "Not a file"); } FileInputStream in=NewFileInputStream (srcfile); FileOutputStream out=NewFileOutputStream (destfile); intC;  while((c = in.read ())!=-1) {out.write (c);        Out.flush ();        } in.close ();    Out.close (); }    }


2. Character Stream
1) Coding issues
2) Recognize text and text files
Java text (char) is a 16-bit unsigned integer, which is the Unicode encoding of the character (double-byte encoding)
File is a byte of byte byte ... The data series
A text file is a stored result of a sequence of text (char) serialized into Byte according to an encoding scheme (UTF-8,UTF-16BE,GBK)
3) Character stream (Reader Writer)----> operation is text text file
Processing of characters, one character at a time
The bottom of the character is still the basic byte sequence
Basic implementation of character stream
InputStreamReader completes a byte stream parsing to a char stream, parsed by encoding
OutputStreamWriter provides a char stream to a byte stream, which is processed by encoding

Filereader/filewriter
Filter for character streams
BufferedReader---->readline read one line at a time
Bufferedwriter/printwriter----> Write a line


3. Serialization of objects, deserialization
1) object serialization, that is, the object is converted to a byte sequence, the inverse is called the deserialization of objects
2) serialized Stream (ObjectOutputStream), is the filter stream----writeobject
Deserialization stream (ObjectInputStream)---readobject

3) serialization Interface (Serializable)
Object must implement a serialization interface for serialization, or an exception will occur
This interface, without any method, is just a standard

4) Transient keywords
private void WriteObject (Java.io.ObjectOutputStream s)
Throws Java.io.IOException
private void ReadObject (Java.io.ObjectInputStream s)
Throws Java.io.IOException, ClassNotFoundException

 PackageCom.imooc.io;Importjava.io.Serializable; Public classStudentImplementsserializable{PrivateString Stuno; PrivateString Stuname; //the element does not serialize the JVM by default, or it can do its own serialization of this element    Private transient intStuage;  PublicStudent (String Stuno, String stuname,intstuage) {        Super();  This. Stuno =Stuno;  This. Stuname =Stuname;  This. Stuage =Stuage; }     PublicString Getstuno () {returnStuno; }     Public voidSetstuno (String stuno) { This. Stuno =Stuno; }     PublicString Getstuname () {returnStuname; }     Public voidsetstuname (String stuname) { This. Stuname =Stuname; }     Public intGetstuage () {returnStuage; }     Public voidSetstuage (intstuage) {         This. Stuage =Stuage; } @Override PublicString toString () {return"Student [stuno=" + Stuno + ", stuname=" + Stuname + ", stuage=" + Stuage + "]"; }     Private voidWriteObject (java.io.ObjectOutputStream s)throwsjava.io.ioexception{s.defaultwriteobject ();//serialization of elements that the JVM can default to serializeS.writeint (Stuage);//self-fulfilling stuage serialization     }     Private voidReadObject (java.io.ObjectInputStream s)throwsjava.io.IOException, classnotfoundexception{s.defaultreadobject ();//Deserializes an element that the JVM can default to deserialize           This. Stuage = S.readint ();//complete the deserialization of the stuage yourself    }}


Analyzing the problems of serialization and deserialization in ArrayList source code

5) Serialization of the call problem for the neutron class and the parent class constructor






Java I/O stream

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.