Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.FileChannel;
NIO Read Data
public class Nioreadandwrite {
public void Readtest (File fileName) {
String content = null;
FileInputStream FIS = null;
FileChannel FC = null;
try {
FIS = new FileInputStream (fileName);
FC = Fis.getchannel ();
Bytebuffer BB = bytebuffer.allocate (10000);
Fc.read (BB);
Bb.flip ();
Content = new String (Bb.array ());
SYSTEM.OUT.PRINTLN (content);
Fc.close ();
Fis.close ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
NIO Write Data
public void writetest (file file) {
String str = "DFKVMLSMVHSDGKAHKANCKJBASDCHBSDKCSKLCNJSBCKJSBCVLS";
FileOutputStream fos = null;
FileChannel FC = null;
Byte[] B = str.getbytes ();
System.out.println (Str.getbytes ());
try {
FOS = new FileOutputStream (file,true);
FC = Fos.getchannel ();
Bytebuffer BB = bytebuffer.allocate (b.length);
Bb.put (b);
Bb.flip ();
Fc.write (BB);
Fc.close ();
Fos.close ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
NIO copy Data
public void CopyFile (String oldpath,string newpath) throws ioexception{
Long starttime = System.currenttimemillis ();
Bytebuffer BB = bytebuffer.allocate (100000);
File Oldf = new file (OldPath);
File Newf = new file (NewPath);
if (!newf.exists ()) {
Newf.mkdirs ();
}
int len =-1;
File temp = null;
string[] list = Oldf.list ();
for (int i=0;i<list.length;i++) {
if (Oldpath.endswith (File.separator)) {
temp = new File (Oldpath+list[i]);
}else{
temp = new File (Oldpath+file.separator+list[i]);
}
System.out.println (Temp.isfile ());
if (Temp.isfile ()) {
FileInputStream fis = new FileInputStream (temp);
FileChannel in = Fis.getchannel ();
FileOutputStream fos = new FileOutputStream (newf+ "/" +temp.getname (). toString ());
FileChannel out = Fos.getchannel ();
while ((Len=in.read (BB))!=-1) {
Bb.flip ();
Out.write (BB);
Bb.clear ();
}
Out.close ();
Fos.close ();
In.close ();
Fis.close ();
}
if (Temp.isdirectory ()) {
CopyFile (oldpath+ "/" +list[i], newpath+ "/" +list[i]);
}
}
Long endtime = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Total length of reproduction:" + (Endtime-starttime));
}
public static void Main (string[] args) throws ioexception{
File File = new file ("D:/test.txt");
String oldfile = "d:\\vc98";
String newFile = "e:/Cheetah download/111";
New Nioreadandwrite (). readtest (file);
New Nioreadandwrite (). writetest (file);
New Nioreadandwrite (). CopyFile (Oldfile,newfile);
}
}