通过字节流复制大文件内容到指定的文件

package com.neusoft.copyfile;


/**
 * @time  2014-8-15 上午10:32:46
 * @author new
 * @function 复制文件内容到指定的文件
 * 
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 
 */
public class CopyFileByStream {

	public static void main(String[] args) throws IOException {
		
		long start=System.currentTimeMillis();
		
		CopyFileByStream cFileByStream=new CopyFileByStream();
		// 创建一个 FileInputStream对象 
		String oldFileName="123.avi";
		String newFileName="copy_"+oldFileName;
		File oldFile=new File(oldFileName);
		File newFile=new File(newFileName);
		if (oldFile.exists()) {
			if (!newFile.exists()) {
				cFileByStream.copyFile(oldFile, newFile);
			}else {
				System.out.println("老大,"+newFileName+"文件已经存在,我马上着手删除!");
				newFile.delete();
				cFileByStream.copyFile(oldFile, newFile);
				System.out.println("老大,"+newFileName+"文件已经准备好,请用!");
			}
		}else {
			System.out.println("老大,你说的那个文件我没找到啊,我停下啦,您再找找,小弟我无能为力了!");
		}
        long end=System.currentTimeMillis();
        System.out.println((end-start)/1000.0+"秒");
		System.out.println("结束");
	}
	
	/**
	 * @function 复制文件
	 * @param oldFile
	 * @param newFile
	 * @throws IOException
	 */
	public void copyFile(File oldFile,File newFile) throws IOException{
		FileInputStream fInputStream=new  FileInputStream(oldFile);
		FileOutputStream fOutputStream=new FileOutputStream(newFile,true);
		// 确定文件的大小
		//int fileSize = fInputStream.available();
		
		byte[] strByte = new byte[1024*1024*2];
		System.out.println("设置的缓冲区大小:"+strByte.length/1024.0+"K");
		int len=0;
		int count=0;
        while((len=fInputStream.read(strByte))!= -1){
           // String str1=new String(strByte);
            System.out.println(len/1024.0+"K 缓冲区循环第"+(++count)+"次");
            fOutputStream.write(strByte,0,len);     
        }
        
        fOutputStream.close();
        fInputStream.close();
	}

}
控制台显示结果:
老大,copy_123.avi文件已经存在,我马上着手删除!
设置的缓冲区大小:2048.0K
2048.0K 缓冲区循环第1次
2048.0K 缓冲区循环第2次

2048.0K 缓冲区循环第3次

.......

2048.0K 缓冲区循环第77次
2048.0K 缓冲区循环第78次
2048.0K 缓冲区循环第79次
415.140625K 缓冲区循环第80次
老大,copy_123.avi文件已经准备好,请用!
3.484秒
结束

posted on 2014-08-16 06:51  亲吻昨日的阳光  阅读(154)  评论(0编辑  收藏  举报

导航