Java Programming Thought learning note _5 (io Stream)

Source: Internet
Author: User

first, read characters with DataInputStream

You can use the available method to see how many characters are available for access. examples are as follows:

 public class Test1 {    publicstaticvoidthrows  IOException {        DataInputStreamin =new datainputstream ( new Bufferedinputstream (new FileInputStream ("test.txt"));          while (in.available ()!=0) {            System.out.println ((char) in.readbyte ());        }        In.close ();    }}

second, New I/O

  1.The main differences between Javanio and IO :

The first major difference between Java NiO and Io is that IO is stream-oriented and NiO is Buffer-oriented. The Java io-oriented stream means that one or more bytes are read from the stream every time, until all bytes are read, and they are not being slowed anywhere. In addition, it cannot move data in the stream back and Forth. If you need to move the data read from the stream before and after it, you need to cache it to a buffer first. Java NiO has a slightly different buffer-oriented Approach. The data is read to a buffer that it processes later, and can be moved back and forth in the buffer if Needed. This increases the flexibility of the PROCESS. however, You also need to check if the buffer contains all the data that you need to process. also, make sure that when more data is read into the buffer, do not overwrite the data that has not been processed in the Buffer.

2. Important interface : Channel interface and Buffer interface. The increase in speed comes from the way in which the structure used is closer to how the operating system executes io: channels and Buffers. We interact with the buffer (buffer) and dispatch the buffer to the Channel. There are three class libraries in the old IO class that can be used to generate filechannel, respectively, fileinputstream, fileoutputstream, randomaccessfile. The only buffer that interacts with the channel is Bytebuffer. Here is an example of an example that produces a writable, readable, readable, and writable Channel.

 public classGetchannel {Private Static Final intbsize=1024;  public Static voidMain (string[] Args)throwsException {filechannel FC=NewFileOutputStream ("data.txt"). Getchannel (); //Write OperationsFc.write (bytebuffer.wrap ("hello my". GetBytes ()));        Fc.close (); FC=NewRandomaccessfile ("data.txt", "rw"). Getchannel ();        Fc.position (fc.size ()); Fc.write (bytebuffer.wrap ("wife xyy". GetBytes ()));        Fc.close (); //Read OperationsFc=NewFileInputStream ("data.txt"). Getchannel (); Bytebuffer Buff=bytebuffer.allocate (bsize);        Fc.read (buff);    Buff.flip (); //Once you call read to tell FileChannel to store bytes to bytebuffer, you must call flip on the buffer to make it a good byte for others to Read.         while(buff.hasremaining ()) {System.out.print (Char) Buff.get ()); }    }}

One way to store bytes in Bytebuffer is to use a "put" method to populate it directly or to "wrap" the resulting byte array into bytebuffer using the Wrap Method. We use Randomaccessfile again to open the data.txt, at this time can use the position method arbitrarily move the pointer, full read and write Operations. For read-only operations, You can use the static allocate method to assign Bytebuffer Directly. Note that when the buffer needs to be read, you need to call the Filp method, which places the maximum writable position of the container at the position of the current pointer, and then positions the current pointer at 0 to prepare for Reading.

3. convert Data . Buffers contain ordinary characters, and in order to convert them into characters, we either encode them as they are entered, or encode them from the buffer when they are entered. You can use the Java.nio.CharSet class to implement these features, as in the following example:

 public classBuffertotext {Private Static Final intbsize=1024;  public Static voidMain (string[] Args)throwsException{filechannel FC=NewFileOutputStream ("data2.txt"). Getchannel (); Fc.write (bytebuffer.wrap ("some text". GetBytes ()));        Fc.close (); FC=NewFileInputStream ("data2.txt"). Getchannel (); Bytebuffer Buff=bytebuffer.allocate (bsize);        Fc.read (buff);        Buff.flip ();        System.out.println (buff.ascharbuffer ()); String encoding=system.getproperty ("file.encoding"); //the first Method. The CharSet forname method is used to decode the bytes contained in the Bytebuffer.System.out.println (encoding+ ":" +charset.forname (encoding). Decode (buff)); //or encode it at the time of Input.Fc=NewFileOutputStream ("data2.txt"). Getchannel (); Fc.write (bytebuffer.wrap ("hello my love". getBytes ("utf-16be")));        Fc.close (); FC=NewFileInputStream ("data2.txt"). Getchannel ();        Buff.clear ();        Fc.read (buff);        Buff.flip ();        System.out.println (buff.ascharbuffer ()); //use Charbuffer when Writing.Fc=NewFileOutputStream ("data2.txt"). Getchannel (); Buff=bytebuffer.allocate (24); Buff.ascharbuffer (). put ("some text");        Fc.write (buff);        Fc.close (); FC=NewFileInputStream ("data2.txt"). Getchannel ();        Buff.clear ();        Fc.read (buff);        Buff.flip ();    System.out.println (buff.ascharbuffer ()); }}

4. Dispersion and aggregation

 Java NiO begins to support Scatter/gather operations, which are used to describe the operations that are read from or written to the channel from the Channel.
Dispersion means that reading from the channel is the writing of the read data to multiple buffer in the read Operation. therefore, the channel will "scatter" the data read from the channel into multiple buffer.
Aggregation refers to the writing of multiple buffer data to the same channel, so that the channel will be more than one buffer in the "aggregation" of data sent to the Channel.

Examples of dispersion are as follows:

Bytebuffer Header = bytebuffer.allocate (+);  Bytebuffer body   = bytebuffer.allocate (1024x768);     = {header, body};    Channel.read (bufferarray);  

Examples of aggregation are as Follows:

Bytebuffer Header = bytebuffer.allocate (+);  Bytebuffer body   = bytebuffer.allocate (1024x768);     // write data into buffers      = {header, body};    Channel.write (bufferarray);  

5. data transfer between channels

The Transferfrom () method of

FileChannel can transfer data from the source channel to filechannel, and the first parameter of the method means that the data is written to the destination file starting at the position , count represents the maximum number of bytes Transferred. If the remaining space of the source channel is less than count bytes, the number of bytes transferred is less than the number of bytes Requested. The  transferto () method transfers data from the FileChannel to the other channel, with the remaining parameters the same as the Transferfrom Method. The following example finishes copying a file:

 public  class   TransferTo { static  final  int  bsize=1024< Span style= "color: #000000;"    >;  public  static  void  main (string[] Args) throws   IOException {filechannel in  =new  fileinputstream ("c:/a.txt" ). Getchannel (); FileChannel out  =new  fileoutputstream ("c:/c.txt"         0

6. Memory mapped file

memory-mapped files allow us to create and modify files that are too large to fit into memory. With a memory-mapped file, you can assume it is in memory and access it as a large array.

FileChannel provides a map method for mapping files to memory image files: Mappedbytebuffer map (int mode,long Position,long size); You can map the size of a file from position to a memory image file, mode indicates how the memory image file can be accessed: Read_only,read_write,private.
A. read_only, (read-only): attempting to modify the resulting buffer will cause the readonlybufferexception to be thrown. (mapmode.read_only)
B. Read_write (read/write): changes to the resulting buffer will eventually propagate to the file; the change is not necessarily visible to other programs that map to the same file. (mapmode.read_write)
C. Private (private): changes to the resulting buffer are not propagated to the file, and the change is not visible to other programs that map to the same file; instead, a private copy of the modified portion of the buffer is Created. (mapmode.private). Here is a simple example of a memory-mapped file that tests the speed comparison of memory-mapped files and normal bytebuffer when writing Data:

 public classChannelTest1 { public Static voidMain (string[] Args)throwsIOException {filechannel FC=NewRandomaccessfile ("c:/cd.txt", "rw"). Getchannel (); Charbuffer CB=fc.map (filechannel.mapmode.read_write,0, 1024). Ascharbuffer (); Bytebuffer buf=bytebuffer.allocate (1024); Charbuffer Cbuf=Buf.ascharbuffer (); LongOldtime=System.nanotime ();  for(inti=200;i<200;i++) {cb.put (""+i); }        LongLasttime=System.nanotime ();  for(inti=200;i<200;i++) {cbuf.put (""+i);        } fc.read (buf); LongEndtime=System.nanotime (); System.out.println (lasttime-oldtime);//821System.out.println (endtime-lasttime);//481950    }}

The more data you actually write, the faster it will be Written.

III. serialization of objects

  1. Serialization Control:

The serialization can be controlled by implementing the Externalizable interface instead of implementing the Serializable Interface. In addition to completing the functions of the serializable interface, the interface adds two methods: writeexternal () and readexternal (), which are called automatically when the restore process is serialized and deserialized to perform special operations.

 public classTest2 { public Static voidMain (string[] Args)throwsioexception, classnotfoundexception {Blip Blip=NewBlip (); Blip.setstr ("puppy"); Bytearrayoutputstream Bos=NewBytearrayoutputstream (); ObjectOutputStream Oos=NewObjectOutputStream (bos);        Oos.writeobject (blip); Bytearrayinputstream bis=NewBytearrayinputstream (bos.tobytearray ()); ObjectInputStream Ois=NewObjectInputStream (bis); Blip b=(Blip) Ois.readobject ();    System.out.println (b); }}classBlipImplementsexternalizable {PrivateString str;  publicBlip () {System.out.println ("the constructor is execute"); }          publicString getstr () {returnstr; }     public voidsetstr (String Str) { this. str =str; } @Override publicString toString () {return"Blip [str=" + str + "]"; } @Override public voidWriteexternal (objectoutput Out)throwsIOException {System.out.println ("write is execute"); Out.writeobject (str);//is necessary for variable initialization} @Override public voidReadexternal (objectinput In)throwsioexception, classnotfoundexception {str=(String) In.readobject (); System.out.println ("read is execute"); }    }

Console printing:

the constructor is Executewrite are Executethe constructor is Executeread are executeblip [str= puppies]

When you restore b, the default constructor is called, so unlike serinable serialization, it must initialize its members within Writeexternal and readexernal, as well as ensure that the object must have a default constructor, or it will get an error.

2. Transient key words

When a member variable is transient, it is not automatically saved to disk, and the automatic serialization mechanism does not attempt to recover it. When the object is restored, the value of the member variable is Null.

Java Programming Thought learning note _5 (io 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.