欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java拷贝文件夹和删除文件夹

程序员文章站 2023-03-26 14:37:38
1.文件夹的拷贝 public void copy(File src, File dest) throws IOException { if (dest.isFile()) { throw new RuntimeException(dest + "不是文件夹"); } File file = new ......

1.文件夹的拷贝

public void copy(file src, file dest) throws ioexception {
  if (dest.isfile()) {
    throw new runtimeexception(dest + "不是文件夹");
  }
  file file = new file(dest.getpath() + "/" + src.getname());
  if (src.isfile()) {
    fileinputstream fis = new fileinputstream(src);
    bufferedinputstream bis = new bufferedinputstream(fis);
    fileoutputstream fos = new fileoutputstream(file);
    bufferedoutputstream bos = new bufferedoutputstream(fos);
    byte[] bytes = new byte[1024];
    int len;
    while ((len = bis.read(bytes)) != -1) {
      bos.write(bytes, 0, len);
    }

    bis.close();
    fis.close();
    bos.close();
    fos.close();

  } else if(src.isdirectory()){
    file.mkdir();
    file[] files = src.listfiles();
    for (file file2 : files) {
      copy(file2, dest);
    }
  }
}

2. 删除整个文件夹:

public void delete(file dir) {
  if (dir.isdirectory()) {
    file[] files = dir.listfiles();
    for (file file : files) {
      delete(file);
    }
  }
  dir.delete();
}