java io流 文件的读取与复制

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
//java FileCopyDemo src dist
/*
* 1.获得命令行参数(来源文件路径和目标文件路径)
* 2.判断来源文件是否存在,如果不存在,提示错误,结束。否则继续
* 3.判断目标文件是否存在,如果存在,提示是否覆盖,如果不覆盖,结束。否则继续
* 4.创建来源文件输入流
* 5.创建目标文件输出流
* 6.创建临时存储字节对象buffer
* 7.循环读取来源文件并将数据写入目标文件输出流
* 8.关闭输入和流出流
* */
public class FileCopyDemo {

public static void main(String[] args) {
if(args.length==2){
String src=args[0];//拷贝来源
String dist=args[1];//拷贝到目标位置
File srcFile=new File(src);
//判断拷贝来源是否存在
//File file=new File(src);
if(srcFile.exists()){
File distFile=new File(dist);
if(distFile.exists()){
Scanner scan=new Scanner(System.in);
System.out.println("文件存在,是否覆盖[N/y]");
String command=scan.next();
if("N".equals(command)){
return;
}
}
FileInputStream srcFin=null;
FileOutputStream distFos=null;
try{
srcFin=new FileInputStream(srcFile);
distFos=new FileOutputStream(distFile);
//文件开始拷贝
byte[]buffer=new byte[1024];
int count=0;
while((count=srcFin.read(buffer))>0){
distFos.write(buffer,0,count);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(srcFin!=null){
try{
srcFin.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(distFos!=null){
try{
distFos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

}else{
System.out.println("来源文件不存在,请检查");
}
}else{
System.out.println("参数输入错误,请检查!");
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值