下面是我写的字节流复制多级文件夹及其文件案例。
类名是:CopyDir
希望各位多提提优化建议!!!- <b><font size="3">package cn.itcast_02;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class CopyDirDemo {
- public static void main(String[] args) throws IOException {
- File srcFolder = new File("D:\\copy1");
- File destFolder = new File("D:\\copy2");
- copyDir(srcFolder, destFolder);
- }
- public static void copyDir(File srcFolder, File destFolder) throws IOException {
- if (!destFolder.exists()) {
- destFolder.mkdir();
- }
- File[] array = srcFolder.listFiles();
- for (File file : array) {
- if (file.isFile()) {
- copyFile(new File(srcFolder, file.getName()), new File(destFolder, file.getName()));
- } else {
- copyDir(new File(srcFolder, file.getName()), new File(destFolder, file.getName()));
- }
- }
- }
- public static void copyFile(File srcFolder, File destFolder) throws IOException {
- FileOutputStream fos = new FileOutputStream(destFolder);
- FileInputStream fis = new FileInputStream(srcFolder);
- byte[] bys = new byte[1024];
- int len = 0;
- while ((len = fis.read(bys)) != -1) {
- fos.write(bys, 0, len);
- }
- fos.close();
- fis.close();
- }
- }</font></b>
复制代码
|
|