黑马程序员技术交流社区

标题: 复制文件夹的问题 [打印本页]

作者: 那片天空    时间: 2014-6-30 23:05
标题: 复制文件夹的问题
package mianshi_copywenjianjia;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CopyFile {
public static void main(String[] args) throws IOException {
  ArrayList<File> al = new ArrayList<File>();
  File file = new File("d:/aaaaa");
  List<File> list = new CopyCaoZuo().getList(file);
  // System.out.println(list.size());
  File file2 = new File("d:/bbbb");
  for (File lst : list) {
  
   if (lst.isDirectory()) {
    String slst1 = lst.getAbsolutePath();
    String slst2 = file.getAbsolutePath();
    String slst3 = slst1.substring(slst2.length(), slst1.length());
    String slst5 = file2.getAbsolutePath() + slst3;
    String slst4 = slst5.replace("\\", "[url=]\\\\[/url]");
    File file6 = new File(slst5);
    file6.mkdirs();
    System.out.println(file6);
   } else {
    al.add(lst);
   }
  }
  for (File l : al) {
   String slst1 = l.getAbsolutePath();
   String slst2 = file.getAbsolutePath();
   String slst3 = slst1.substring(slst2.length(), slst1.length());
   String slst5 = file2.getAbsolutePath() + slst3;
   System.out.println(slst5);
   String slst4 = slst5.replace("\\", "[url=]\\\\[/url]");
   System.out.println(l);
   System.out.println(slst4);
   //new CopyCaoZuo().copy(l,slst4);
  }
}
}
class CopyCaoZuo {
// 创建File集合
ArrayList<File> list = new ArrayList<File>();
// 该文件夹内所以文件及文件夹对象,并添加到集合
public List<File> getList(File file) {
  // 获取当前文件夹下得所以文件及文件夹对象数组
  File[] f = file.listFiles();
  // 遍历数组
  for (File fil : f) {
   // 如果是文件夹就继续调用getList方法
   if (fil.isDirectory()) {
    getList(fil);
   }
   // 将得到的文件及文件夹对象添加到集合
   list.add(fil);
  }
  return list;
}
public void copy(File lst, String slst4) throws IOException {
//  if (!file2.exists()) {
//   file2.mkdirs();
//  }
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    lst));
  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(new File(slst4)));
  byte[] by = new byte[1024];
  int len = 0;
  while ((len = bis.read(by)) != -1) {
   bos.write(by, 0, len);
  }
  bos.close();
  bis.close();
}
}
为什么只复制了空文件夹,里边的文件没复制呢,求解?

作者: 不去会死    时间: 2014-7-1 08:40
能不能整理一下代码,看下去的欲望都没有
作者: 那片天空    时间: 2014-7-1 13:01
问题已解决;
        是因为太乱了,File file6 = new File(slst5);这传错了变量了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2