Java file moving routine four methods and using Filecopyutils.copy (,) method

Source: Internet
Author: User
Tags file copy getmessage

Using Java for file copy I believe many people will use, but is it the best efficiency?
Recently I looked at NiO and decided to try the performance improvement of Java NIO.

The first method: The old way public static long Forjava (File f1,file F2) throws exception{
Long time= new Date (). GetTime ();
int length=2097152;
FileInputStream in= New FileInputStream (F1);
FileOutputStream out= New FileOutputStream (F2);
Byte[] buffer= new byte[length];
while (true) {
int ins=in.read (buffer);
if (ins==-1) {
In.close ();
Out.flush ();
Out.close ();
return new Date (). GetTime ()-time;
} else
Out.write (Buffer,0,ins);
}
}

The 2 parameters of the method are the original file, and the destination file of the copy. There is not much to introduce here.

The implementation method is very simple, constructs the input output stream to 2 files separately, and uses a byte array as our memory buffer, then uses the stream to read out the data to the cache in the F1, writes the cache data to the F2 inside. The cache here is a byte array of 2MB

2nd method: Use pipes in NIO to pipeline transport public static long Fortransfer (File f1,file F2) throws exception{
Long time= new Date (). GetTime ();
int length=2097152;
FileInputStream in= New FileInputStream (F1);
FileOutputStream out= New FileOutputStream (F2);
FileChannel Inc=in.getchannel ();
FileChannel Outc=out.getchannel ();
int i=0;
while (true) {
if (Inc.position () ==inc.size ()) {
Inc.close ();
Outc.close ();
return new Date (). GetTime ()-time;
}
if ((Inc.size ()-inc.position ()) <20971520)
length= (int) (Inc.size ()-inc.position ());
Else
length=20971520;
Inc.transferto (Inc.position (), LENGTH,OUTC);
Inc.position (Inc.position () +length);
i++;
}
}

Implementation method: On the basis of the first implementation of the input and output stream to obtain its pipeline, and then the batch from the F1 pipeline like F2 in the pipeline input data each input data maximum of 2MB

Method 3: Memory file Scene write (read the file does not use a file scene, interested can go back to try, I will not try, estimate will be faster) public static long forimage (file F1,file F2) throws exception{
Long time= new Date (). GetTime ();
int length=2097152;
FileInputStream in= New FileInputStream (F1);
Randomaccessfile out= New Randomaccessfile (F2, "RW");
FileChannel Inc=in.getchannel ();
Mappedbytebuffer outc= null;
Mappedbytebuffer inbuffer= null;
Byte[] b= new byte[length];
while (true) {
if (Inc.position () ==inc.size ()) {
Inc.close ();
Outc.force ();
Out.close ();
return new Date (). GetTime ()-time;
}
if ((Inc.size ()-inc.position ()) <length) {
length= (int) (Inc.size ()-inc.position ());
} else{
length=20971520;
}
b= New Byte[length];
Inbuffer=inc.map (Mapmode.read_only,inc.position (), length);
Inbuffer.load ();
Inbuffer.get (b);
Outc=out.getchannel (). Map (Mapmode.read_write,inc.position (), length);
Inc.position (B.length+inc.position ());
Outc.put (b);
Outc.force ();
}
}

Implementation: Unlike 2 examples, the write file stream does not use a pipeline but rather uses a memory file map (assuming that the file is F2 in memory). Reads data from a F1 pipeline into a byte array in a loop, and then writes the data in a F2 file like a memory map.

4th method: Pipe to pipe public static long Forchannel (File f1,file F2) throws exception{
Long time= new Date (). GetTime ();
int length=2097152;
FileInputStream in= New FileInputStream (F1);
FileOutputStream out= New FileOutputStream (F2);
FileChannel Inc=in.getchannel ();
FileChannel Outc=out.getchannel ();
Bytebuffer b= null;
while (true) {
if (Inc.position () ==inc.size ()) {
Inc.close ();
Outc.close ();
return new Date (). GetTime ()-time;
}
if ((Inc.size ()-inc.position ()) <length) {
length= (int) (Inc.size ()-inc.position ());
} else
length=2097152;
B=bytebuffer.allocatedirect (length);
Inc.read (b);
B.flip ();
Outc.write (b);
Outc.force (FALSE);
}
}

The implementation here is similar to the 3rd implementation, but no memory innuendo is used.

The following is the test time for copying 49.3MB files (milliseconds)

Start Copy file ... file size:50290kb
COPYFILE:B1.RMVB Mode:forchannel runtime:3203
COPYFILE:B1.RMVB Mode:forimage runtime:3328
COPYFILE:B1.RMVB Mode:forjava runtime:2172
COPYFILE:B1.RMVB Mode:fortransfer runtime:1406
End Copy file!



PS: This is an upload method with the Uploadify plugin

Public Returnobject UploadFile (String deletefilename,
HttpServletRequest request,httpservletresponse Response)
Throws ioexception{
SYSTEM.OUT.PRINTLN ("Attachment upload sessioninfo:"
+ contextutils.getsession (). GetId ());
String basepath = Global.base_upload_folder; Get the underlying path
String temporaryfile=global.base_upload_temporaryfile;//Get temporary folder
Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
map<string,multipartfile> Filemap = Multipartrequest.getfilemap ();
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss");
SimpleDateFormat sp = new SimpleDateFormat ("YyyyMMdd");
TODO multi-tenant.id Current Tenant ID is 707 after perfect multi-tenant.id is tenant ID
String Ctxpath = basepath + file.separator + 707 + file.separator
+ Contextutils.getcurrentsecurityuser (). GetUserName ()
+ file.separator+temporaryfile+file.separator;//Full path
String Ctxpathview = Sp.format (New Date ()) + "/";//For the path that is stored in the database-starting from the folder
String ymd = Sdf.format (New Date ());
If it does not exist, create a folder
File File = new file (Ctxpath);
if (!file.exists ()) {
File.mkdirs ();
}
Returnobject ro = new Returnobject ();
String fileNames = "";
For (map.entry<string,multipartfile> Entity:fileMap.entrySet ()) {
Multipartfile MF = entity.getvalue ();
String filefullname = Mf.getoriginalfilename ();
String fileName = Mf.getoriginalfilename ();
String fileName = Ymd + "_" + filefullname;
File UploadFile = new file (Ctxpath + fileName);
try{
filecopyutils.copy (Mf.getbytes (), uploadfile)//can use this method to move files, move directly through the stream
Save upload data record after copy succeeds
UploadFile Uploadbean = new UploadFile ();
Uploadbean.setupduser (Contextutils.getcurrentsecurityuser ()
. GetUserName ());
Uploadbean.setoriginname (Filefullname);
Uploadbean.setfilename (FileName);
Uploadbean.setupdtime (New Date ());
Uploadbean.setisfunction ("other");
if (Uploadbean!= null) {
Uploadfileservice.save (Uploadbean);
}
FileNames + = FileName + ",";
}
catch (IOException e) {
E.printstacktrace ();
Ro.setsuccess (FALSE);
Ro.setmsg (E.getmessage ());
return ro;
}
}
if (Filenames.endswith (",")) {
FileNames = filenames.substring (0,filenames.length ()-1);
}
Ro.setsuccess (TRUE);
Ro.setmsg ("Upload file Success");
hashmap<string,object> hsfiled = new hashmap<string,object> ();
Hsfiled.put ("FileNames", fileNames);
Hsfiled.put ("Filepatch", ctxpathview);//Database save path (intercepted from time)
Ro.setobj (hsfiled);
Empty history files that you don't need
try{
Log.info ("Delete unwanted files:" + deletefilename);
String Ctpath = basepath + file.separator + file.separator
+ Deletefilename;
If it does not exist, create a folder
if (deletefilename!= null) {
File Filetobedelete = new file (Ctpath);
if (filetobedelete.exists ()) {
Filetobedelete.delete ();
}
}
}
catch (Exception e) {
Log.error ("Delete history file Error:" + e.getmessage ());
}
return ro;
}

Related Article

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.