利用遞歸實現將某個目錄下所有內容copy到另一個目錄中。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* 利用遞歸實現將某個目錄下所有內容copy到另一個目錄中。
*/
public class Demo2 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入要複製的文件夾:");
File source = new File(sc.next());
System.out.println("請輸入要複製到的目標文件夾");
File dest = new File(sc.next());
Demo2.digui(source, dest);
}
/**
*
* @param source 要複製的文件
* @param dest 要複製到的目標文件夾
* @throws IOException
*/
public static void digui(File source,File dest) throws IOException {
//如果要複製的文件存在
if(source.exists()) {
//如果複製的文件是文件夾
if(source.isDirectory()) {
//在目標文件夾創建這個文件夾
File file = new File(dest+"/"+source.getName());
file.mkdirs();
File[] lf = source.listFiles();
if(lf!=null&&lf.length>0) {
for(File ff:lf) {
digui(ff,file);
}
}
}else {//如果複製的文件是文件,則進行文件的複製
BufferedReader br = new BufferedReader(new FileReader(source));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest+"/"+source.getName()));
String s = "";
while((s=br.readLine())!=null) {
bw.write(s);
}
bw.close();
br.close();
}
}
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* 利用遞歸實現將某個目錄下所有內容copy到另一個目錄中。
*/
public class Demo2 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入要複製的文件夾:");
File source = new File(sc.next());
System.out.println("請輸入要複製到的目標文件夾");
File dest = new File(sc.next());
Demo2.digui(source, dest);
}
/**
*
* @param source 要複製的文件
* @param dest 要複製到的目標文件夾
* @throws IOException
*/
public static void digui(File source,File dest) throws IOException {
//如果要複製的文件存在
if(source.exists()) {
//如果複製的文件是文件夾
if(source.isDirectory()) {
//在目標文件夾創建這個文件夾
File file = new File(dest+"/"+source.getName());
file.mkdirs();
File[] lf = source.listFiles();
if(lf!=null&&lf.length>0) {
for(File ff:lf) {
digui(ff,file);
}
}
}else {//如果複製的文件是文件,則進行文件的複製
BufferedReader br = new BufferedReader(new FileReader(source));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest+"/"+source.getName()));
String s = "";
while((s=br.readLine())!=null) {
bw.write(s);
}
bw.close();
br.close();
}
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.