Java程序片:Java复制文件
第一种方法(输入输出流):
public void copyFile(File fromFile,File toFile) throws Exception{ FileInputStream in=new FileInputStream(fromFile); FileOutputStream out=new FileOutputStream(toFile); byte[] buffer=new byte[1024]; while((in.read(buffer))!=-1){ out.write(buffer, 0, buffer.length); } in.close(); out.flush(); out.close(); }
第二种方法(文件通道):
public void fileCopy( File in, File out ) throws IOException { FileChannel inChannel=new FileInputStream(in).getChannel();//得到对应的文件通道 FileChannel outChannel=new FileOutputStream(out).getChannel();//得到对应的文件通道 try{ //inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows // magic number for Windows, 64Mb - 32Kb) int maxCount=(64*1024*1024)-(32*1024); long size=inChannel.size(); long position=0; while(position<size){ position+=inChannel.transferTo(position, maxCount, outChannel);//连接两个通道,并且从in通道读取,然后写入out通道 } }finally { if ( inChannel != null ) { inChannel.close(); } if ( outChannel != null ) { outChannel.close(); } } }
对比:
FileChannel复制文件的速度比输入输出流方式复制文件的速度快。在复制大文件的时候更加体现出FileChannel的速度优势。而且FileChannel是多并发线程安全的。