要求:命令行给定一个文件夹F,以递归的方式分析任意F的目录结构,能够使用流复制该文件夹下所有子文件夹和文件到文件夹下的F(复制) 下。
Copy.java
实现文件的复制
import java.io.*;
public class Copy {
public static void CopyFile(String path,String destPath) throws IOException{
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(path);
fos=new FileOutputStream(destPath);
byte[] bytes=new byte[1024*1024];
int readCount=0;
while((readCount=fis.read(bytes))!=-1){
fos.write(bytes,0,readCount);
}
fos.flush();
fos.close();
}
catch(FileNotFoundException FNFE){
System.out.println("Not Found");
}
}
}
DirectoryReadAndCopy.java
递归遍历目录及目录下的文件,顺便复制
import java.io.*;
import java.util.Scanner;
public class DirectoryReadAndCopy{
public static void readContentsInDirectoryRecursiveAndCopy(String path,int level,String destPath) throws IOException{
File source=new File(path);
File dest=new File(destPath);
if(!dest.exists()){
dest.mkdirs();
}
if(!source.exists()){ //判断文件是否存在
System.out.println("does not exit");
}
else {
try{
File[] fileList=source.listFiles();
for(File mem:fileList){
for(int j=0;j<level;j++){
System.out.print("-");
}
if(mem.isFile()){
Copy.CopyFile(mem.getAbsolutePath(),dest+File.separator+mem.getName());
System.out.println("[File]"+mem.getAbsolutePath());
String curfilepath=mem.getAbsolutePath();
}
else if(mem.isDirectory()){ //递归遍历目录
Copy.CopyFile(mem.getAbsolutePath(), dest+File.separator+mem.getName());
System.out.println("[Directory]"+mem.getAbsolutePath());
readContentsInDirectoryRecursiveAndCopy(mem.getAbsolutePath(), level+2,destPath);
}
}
}
catch(NullPointerException NPE){ //对于不可访问的目录,在调用listFile()时会报错
System.out.println("Can not visit!");
}
}
}
public static void main(String[] args) throws IOException {
String path=args[0]; //命令行第一个参数
String destPath=args[1];
//String path="C:/Users/11757/Desktop/test";
//String destPath="C:/Users/11757/Desktop/test1";
readContentsInDirectoryRecursiveAndCopy(path,2,destPath);
}
}
命令行执行
java DirectoryReadAndCopy.java 源文件路径 目标文件路径