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

文件拷贝:文件字节输入、输出流

程序员文章站 2022-04-09 16:37:33
...

文件拷贝:文件字节输入、输出流

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件拷贝:文件字节输入、输出流
 *
 * 
 *
 */
public class Copy {

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		copy("IO开篇.mp4","IO-copy.mp4"); 
		long t2 = System.currentTimeMillis();
		System.out.println(t2-t1);
	}
	
	public static void copy(String srcPath,String destPath) {
		//1、创建源
			File src = new File(srcPath); //源头
			File dest = new File(destPath);//目的地
			//2、选择流		
			try( InputStream is=new BufferedInputStream(new FileInputStream(src));
					OutputStream os =new BufferedOutputStream( new FileOutputStream(dest));	) {				
				//3、操作 (分段读取)
				byte[] flush = new byte[1024]; //缓冲容器
				int len = -1; //接收长度
				while((len=is.read(flush))!=-1) {
					os.write(flush,0,len); //分段写出
				}			
				os.flush();
			}catch(FileNotFoundException e) {		
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
	}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 文件拷贝:文件字节输入、输出流
 *
 *
 *
 */
public class CopyTxt {

	public static void main(String[] args) {
		copy("abc.txt","abc-copy.txt"); 
	}	
	public static void copy(String srcPath,String destPath) {
		//1、创建源
			File src = new File(srcPath); //源头
			File dest = new File(destPath);//目的地
			//2、选择流		
			try( BufferedReader br=new BufferedReader(new FileReader(src));
					BufferedWriter bw =new BufferedWriter( new FileWriter(dest));	) {				
				//3、操作 (逐行读取)
				String line =null;
				while((line=br.readLine())!=null) {
					bw.write(line); //逐行写出
					bw.newLine();
				}			
				bw.flush();
			}catch(FileNotFoundException e) {		
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
	}
}