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();
}
}
}
}
不知道这个符不符合要求 |