面试题,使用流的方式复制文件

问:  C盘文件夹下的某个文件,复制到  D盘下的文件夹下的文件!  使用流 实现!

package demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Scanner;

public class Copy {
	public static void main(String args[]){
		/*输入源文件路径*/
		System.out.println("请输入源文件路径(如c:\1.txt)");
		Scanner s = new Scanner(System.in);
		String src = s.nextLine();
		System.out.println("源文件路径确认"+src);
		
		/*输入目标路径*/
		System.out.println("请输入目标路径");
		
		String dest = s.nextLine();
		System.out.println("目标路径确认"+dest);
		s.close();
		/*拷贝*/
		try{
			copy(src,dest);
			/*显示是否成功*/
			System.out.println("拷贝完成");
		}catch(Exception e){
			System.out.println("拷贝过程出错");
			System.out.println(e.getMessage());
		}
		
	} 
	
	private static void copy(String src,String dest) throws Exception{
		InputStream is = readFile(src);
		writeToFile(is,dest);
	}
	
	private static InputStream readFile(String src) throws Exception{
		if(!existFile(src)){
			throw new Exception("源文件不存在");
		}
		FileInputStream fis = new FileInputStream(src);
		return fis;
	}
	
	private static boolean existFile(String src) throws Exception{
		File f = new File(src);
		if(f.exists()){
			return true;
		}else{
			return false;
		}
	}
	
	private static void writeToFile(InputStream is,String dest) throws Exception{
		if(!existFile(dest)){
			File f = new File(dest);
			f.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(dest);
		inToOut(is,fos);
	}
	
	private static void inToOut(InputStream is,FileOutputStream fos) throws Exception{
		try{
			int len = 0;
			byte buffer[] = new byte[1024];
			while((len=is.read(buffer))>0){
				fos.write(buffer,0,len);
			}
		}catch(Exception e){
			System.out.println("拷贝失败");
			System.out.println(e.getMessage());
		}finally{
			if(is!=null){
				is.close();
			}
			if(fos!=null){
				fos.close();
			}
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值