thinkjava-New IO

Source: Internet
Author: User
Tags file copy

 PackageCom.java.io;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classGetchannel {Private Static Final intBsize = 1024; @SuppressWarnings ("Resource")       Public Static voidMain (string[] args)throwsException {//Gets the channel that allows write operationsFileChannel FC =NewFileOutputStream ("Data.txt"). Getchannel (); //wrapping a byte array into a bufferFc.write (Bytebuffer.wrap ("Some text". GetBytes ())); //Close ChannelFc.close (); //a pipeline created by a random read-write file streamFC =NewRandomaccessfile ("Data.txt", "RW"). Getchannel (); //fc.position () calculates the number of bytes from the beginning of the file to the current position//sets the file location for this channel, Fc.size () The current size of the file for this channel, after the statement executes, the channel position is at the end of the fileFc.position (Fc.size ());//Move to the endFc.write (Bytebuffer.wrap ("Some More". GetBytes ()));                        Fc.close (); //Read the file:FC =NewFileInputStream ("Data.txt"). Getchannel (); Bytebuffer Buff=bytebuffer.allocate (bsize); //reads the contents of the file into the specified bufferfc.read (Buff); //Buffer.flip (); must have, if not, is from the end of the file to read, of course, read out is the character of the byte=0 time. //by Buffer.flip (); This statement changes the current position of buffer to the first position of the buffer buffers. Buff.flip ();  while(Buff.hasremaining ()) {System.out.print (Char) Buff.get ()); }      }}
View CodeFor read-only access, we must explicitly use the static allocate () method to allocate the Bytebuffer. The goal of NiO is to quickly move large amounts of data, so the size of the bytebuffer is particularly important. One by one in fact, the LK used here may be a little smaller than we usually use (the best size must be found by actually running the application). Once you call read () to tell FileChannel to store bytes to Bytebuffer, you must call Flip () on the buffer. Make it ready for someone else to read the bytes (yes, it seems a bit clumsy, but keep in mind that it's very clumsy, but it works for the maximum speed) if we're going to use a buffer to perform further read () operations, we also have to call clear () to each read () Be prepared. This can be seen in the following simple file copy program:
 PackageCom.java.io;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classchannelcopy {Private Static Final intBsize = 1024;  Public Static voidMain (string[] args)throwsException {if(Args.length! = 2) {System.out.println ("Arguments:sourcefile DestFile"); System.exit (1); } FileChannel in=NewFileInputStream (args[0]). Getchannel (), Out=NewFileOutputStream (args[1]). Getchannel (); Bytebuffer Buffer=bytebuffer.allocate (bsize);  while(In.read (buffer)! =-1) {buffer.flip (); //Prepare for writingout.write (buffer);    Buffer.clear (); //Prepare for reading            }       }}
View CodeAs you can see, open a FileChannel for reading and open another for writing. Bytebuffer is assigned a space when Filechannel.read () returns-1 o'clock (a delimiter, no doubt, the color originates from UNIX and C). Indicates that we have reached the end of the input. After each read () operation, the data is entered into the buffer. Flip () Prepares the buffer so that its information can be extracted by write (). After the write () operation, the information is still in the buffer, and the clear () operation re-arranges all internal pointers so that the buffer is ready to accept the data during another read () operation. However, the above program is not the ideal way to handle such operations. Special Methods Transferto () and Transferfrom () allow us to connect one channel directly to another:
 PackageCom.java.io;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.nio.channels.FileChannel; Public classTransferTo { Public Static voidMain (string[] args)throwsException {if(Args.length! = 2) {System.out.println ("Arguments:sourcefile DestFile"); System.exit (1); } FileChannel in=NewFileInputStream (args[0]). Getchannel (), Out=NewFileOutputStream (args[1]). Getchannel (); In.transferto (0, In.size (), out); //Or://Out.transferfrom (in, 0, in.size ());      }}
View Code

1 Converting DataLook back at Getchannel.java This program will find that in order to output the information in the file, we must read only one byte of data at a time, and then cast each byte type to char type. This method seems a bit primitive--one if we look at the Java.nio.CharBuffer class, we will find that it has a ToString () method that defines: "Returns a String containing all the characters in the buffer. "Since Bytebuffer can be seen as a charbuffer with a Ascharbuffer () method, why not use it?" as the first line in the following output statement does, this method does not solve the problem:
 PackageCom.java.io;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel;ImportJava.nio.charset.Charset; Public classBuffertotext {Private Static Final intBsize = 1024; @SuppressWarnings ("Resource")     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 (); //doesn ' t work:System.out.println (Buff.ascharbuffer ()); //Decode using this system ' s default Charset:Buff.rewind (); String encoding= System.getproperty ("file.encoding"); System.out.println ("Decoded using" + Encoding + ":" +charset.forname (encoding). Decode (buff)); //Or, we could encode with something that would print:FC =NewFileOutputStream ("Data2.txt"). Getchannel (); Fc.write (Bytebuffer.wrap ("Some text". GetBytes ("Utf-16be")));        Fc.close (); //Now try reading again:FC =NewFileInputStream ("Data2.txt"). Getchannel ();        Buff.clear ();        Fc.read (Buff);        Buff.flip ();                System.out.println (Buff.ascharbuffer ()); //Use a charbuffer to write through:FC =NewFileOutputStream ("Data2.txt"). Getchannel (); Buff= Bytebuffer.allocate (24);//More than neededBuff.ascharbuffer (). Put ("Some text");        Fc.write (Buff);                Fc.close (); //Read and display:FC =NewFileInputStream ("Data2.txt"). Getchannel ();        Buff.clear ();        Fc.read (Buff);        Buff.flip ();    System.out.println (Buff.ascharbuffer ()); }}
View CodeBuffers hold normal bytes, and in order to convert them into characters, we either encode them at the time they are entered (so that they have meaning when they are output). Either decode them when they are output from the buffer. You can use the Java.nio.charset.Charset class to implement these features, which provide tools to encode data into a number of different types of character sets

---------------

thinkjava-New IO

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.