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

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();

}


更多了解都可加群:741090028,暗号:小螺号

你可能感兴趣的:(java拷贝文件夹和删除文件夹)