实现文件夹的遍历和复制
1.文件夹遍历
public static void ergodic(String path){
File file = new File(path);
for (File one : file.listFiles()) {
System.out.println("路径:" + one.getPath());
System.out.println("类型:" + one.isDirectory());
// 如果是文件夹,继续获取该子文件夹下面的内容
if (one.isDirectory()) {
for (File f : one.listFiles()) {
System.out.println("=路径:" + f.getPath());
// 检查是否有Directory,有就继续获取.listFiles()
}
}
}
}
这种方法运用了递归的思想。
2.文件夹复制
1.首先进行文件的复制,有两种方法,分别是用字符流和用字节流进行复制
首先用字符流进行复制
/**
* 该方法实现文件的复制
* @param path1 待复制的文件
* @param path2 文件复制到的地址
*/
public static void copy1(String path1, String path2){
FileReader fr;
FileWriter fw;
try {
fr = new FileReader(path1);
try{
fw = new FileWriter(path2);
char [] c = new char [30];
int n = 0;
while (-1 != (n = fr.read(c))){
fw.write(c, 0 ,n);
}
fw.close();
fr.close();
}catch(IOException e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
2.用字节流进行复制
/**
* 该方法实现文件的复制
* @param path1 待复制的文件
* @param path2 文件复制到的地址
*/
public static void copy2(String path1, String path2){
try{
FileInputStream fileReader = new FileInputStream(path1);
try{
FileOutputStream fileWriter = new FileOutputStream(path2);
int n = 0;
byte [] b = new byte [30];
while (-1 != (n = fileReader.read(b))){
fileWriter.write(b, 0, n);
}
fileWriter.close();
fileReader.close();
}catch(IOException e){
e.printStackTrace();
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
注意:字符流只能进行.txt文件的复制,其他的格式要用字节流的方式进行复制。
3.最后用递归的思想进行文件夹的复制,其实质是用递归的方法遍历文件夹,遇到文件就复制
/**
* 该方法实现文件夹的复制
* @param path1 待复制的文件夹
* @param path2 文件夹复制到的地址
*/
public static void copy3(String path1, String path2){
File f1 = new File(path2);
// 获取源文件夹当前下的文件或目录
File file = new File(path1);
if (file.isFile()) {
// 复制文件 ,copy2是上面复制文件的方法
copy2(file.getAbsolutePath(), path2);
System.out.println("sssssssssss");
}
else if (file.isDirectory()) {
f1.mkdirs();
for (File f : file.listFiles()){
String path = path2+"\\" + f.getName();
System.out.println("------------");
// 递归,调用自己
copy3(f.getAbsolutePath(), path);
}
}
}