java文件复制速度_java中文件复制得速度测试
//需要將apache開發的兩個插件包拷到lib目錄下:commons-fileupload-1.2.2.jar ?commons-io-2.0.1.jar package com.nay.servlet; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import
最近,對JAVA中文件復制得方式進行速度測試,得出如下結論,測試方案為:
1.傳統IO包得復制方法:
void?fileByteCopy(String?inFile,String?outFile)?throw*?**ception
{
long?t1=System.currentTimeMillis();
FileInputStream??in?=new?FileInputStream(new?File(inFile));
FileOutputStream?out=new?FileOutputStream(new?File(outFile),true);
byte[]?bytes=new?byte[1024];
int?i;
while((i=in.read(bytes))!=-1)
{
out.write(bytes,0,i);
}
//out.close();
in.close();
out.close();
System.out.println("花費時間"+(System.currentTimeMillis()-t1)+"豪秒");
}
2.新IO包中基于channel和direct?buffer得測試:
void?fileBufferCopy(String?inFile,String?outFile)?throw*?**ception
{
long?t1=System.currentTimeMillis();
//FileInputStream??in?=new?FileInputStream(new?File(inFile));
//FileOutputStream?out=new?FileOutputStream(new?File(outFile));
FileChannel?inChannel=new?FileInputStream(new?File(inFile)).getChannel();
FileChannel?ouChannel=new?FileOutputStream(new?File(outFile)).getChannel();
ByteBuffer?buffer=ByteBuffer.allocateDirect(1024);
//while((int?i=inChannel.read()))
int?i=0;
while(true)
{
buffer.clear();
if((i=inChannel.read(buffer))==-1)
break;
buffer.flip();
ouChannel.write(buffer);
}
//out.close();
inChannel.close();
ouChannel.close();
System.out.println("花費時間"+(System.currentTimeMillis()-t1)+"毫秒");
}
3.直接影射,MappedByteBuffer
void?byteMapFileCopy(String?inFile,String?outFile)?throw*?**ception
long?t1=System.currentTimeMillis();
File?file=new?File(inFile);
FileChannel?out=new?FileOutputStream(new?File(outFile)).getChannel();
//FileInputStream?input=new?FileInputStream(file);
MappedByteBuffer?buffer=new?FileInputStream(file).getChannel().map(FileChannel.MapMode.READ_ONLY,0,file.length());
buffer.load();
//Charset?charset=Charset.defaultCharset();
//Charset?charset=Charset.forName("GBK");
//CharBuffer?charBuffer=charset.decode(buffer);
//System.out.println(charBuffer);
out.write(buffer);
buffer=null;
out.close();
System.out.println("花費時間"+(System.currentTimeMillis()-t1)+"測試");
-------------------------------------------------------------------------------
測試文件大小為:200M,同一windows?xp系統在只運行此應用程序(系統程序等必須除外,忙碌情況相同),得到如下近似結果:
一:傳統IO復制大致消耗時間:9500-15000毫秒
二:direct?buffer方式復制消耗時間:9000-15000毫秒
三:系統影射方式復制大致消耗時間:6000-10000毫秒
從 以上可以看出,單元測試類不能取名為Test 否則即使導入JUnit的包@Test也不好使 #Junit——簡介# xUnit是一套基于測試驅動開發的測試框架 JUnit是xUnit的一套子集,xUnit的子集還有pythonUnit、cppUnit JUnit3:不支持注解,必須繼承junit.framework.TestCase這個類,且命名必第三種方式稍好,不過從后兩種方法得原理可以看出,他們比較依賴系統,因此在系統性能良好得情況下應該要優于傳統得IO復制方式,如果復制 得文件大小在20M-200M之間,我會優先選用第三種方案,不過它會直接把整個文件影射進內存,如果文件非常大得話,不知道此種方案能行通否?
總結
以上是生活随笔為你收集整理的java文件复制速度_java中文件复制得速度测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每个Java应用容器都要包含tomcat
- 下一篇: 顺序三元组 java_三元组顺序结构实现