欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java输入输出流复制文件所用时间对比

程序员文章站 2024-03-13 17:05:27
废话不多说,关键代码如下所述: package com.edu.xynu; import java.io.bufferedinputstream; imp...

废话不多说,关键代码如下所述:

package com.edu.xynu; 
import java.io.bufferedinputstream; 
import java.io.bufferedoutputstream; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
public class iounitcopy { 
//按字节 
public static void copybybyte(file srcfile,file destfile) throws ioexception{ 
fileinputstream fis=new fileinputstream(srcfile); 
fileoutputstream fos=new fileoutputstream(destfile); 
int i; 
while((i=fis.read())!=-1){ 
fos.write(i); 
} 
fis.close(); 
fos.close(); 
} 
//按字节数组 
public static void copybybytearray(file srcfile,file destfile) throws ioexception{ 
fileinputstream fis=new fileinputstream(srcfile); 
fileoutputstream fos=new fileoutputstream(destfile); 
byte []buf=new byte[10*1024]; 
int i; 
while((i=fis.read(buf, 0, buf.length))!=-1){ 
fos.write(buf, 0, i); 
} 
fis.close(); 
fos.close(); 
} 
//字节缓冲流 
public static void copybybuff(file srcfile,file destfile) throws ioexception{ 
bufferedinputstream bis=new bufferedinputstream(new fileinputstream(srcfile)); 
bufferedoutputstream bos=new bufferedoutputstream(new fileoutputstream(destfile)); 
int i; 
while((i=bis.read())!=-1){ 
bos.write(i); 
} 
bos.flush(); 
bis.close(); 
bos.close(); 
} 
//字节数组批量读取 缓冲输出流写入 
public static void copybybuffarray(file srcfile,file destfile) throws ioexception{ 
fileinputstream bis=new fileinputstream(srcfile); 
bufferedoutputstream bos=new bufferedoutputstream(new fileoutputstream(destfile)); 
byte [] buf=new byte[10*1024]; 
int len; 
while((len=bis.read(buf,0,buf.length))!=-1){ 
bos.write(buf,0,len); 
} 
bos.flush(); 
bis.close(); 
bos.close(); 
} 
} 
package com.edu.xynu; 
import java.io.file; 
import java.io.ioexception; 
public class iounitscopytest { 
public static void main(string[] args) { 
// todo auto-generated method stub 
try { 
long start=system.currenttimemillis(); 
// iounitcopy.copybybyte(new file("c:\\1.mp3"), new file( 
// "c:\\2.mp3"));//90713ms 
// iounitcopy.copybybytearray(new file("c:\\1.mp3"), new file( 
// "c:\\3.mp3"));//41ms 
// iounitcopy.copybybuff(new file("c:\\1.mp3"), new file( 
// "c:\\4.mp3"));//556ms 
// iounitcopy.copybybytearray(new file("c:\\1.mp3"), new file( 
// "c:\\5.mp3"));//30ms 
long end=system.currenttimemillis(); 
system.out.println(end-start); 
} catch (ioexception e) { 
// todo auto-generated catch block 
e.printstacktrace(); 
} 
} 
}

测试文件是

Java输入输出流复制文件所用时间对比