目录操作工具类 CopyDir.java
分类:
IT文章
•
2024-07-12 16:46:18
- package com.util;
-
- import java.io.*;
-
- public class CopyDir {
- private File sDir, dDir, newDir;
-
- public CopyDir(String s, String d) {
- this(new File(s), new File(d));
- }
-
- CopyDir(File sDir, File dDir)
- {
- this.sDir = sDir;
- this.dDir = dDir;
- }
-
- public void copyDir() throws IOException {
-
-
- String name = sDir.getName();
-
-
- newDir = dDir;
-
-
- newDir.mkdir();
-
-
- listAll(sDir);
- }
-
-
- private void listAll(File dir) throws IOException {
- File[] files = dir.listFiles();
- for (int x = 0; x < files.length; x++) {
- if (files[x].isDirectory()) {
- createDir(files[x]);
- listAll(files[x]);
- } else {
- createFile(files[x]);
- }
- }
- }
-
-
- private void createDir(File dir) {
- File d = replaceFile(dir);
- d.mkdir();
- }
-
-
- private void createFile(File file) throws IOException {
- File newFile = replaceFile(file);
-
- FileInputStream fis = new FileInputStream(file);
- FileOutputStream fos = new FileOutputStream(newFile);
- byte[] buf = new byte[1024 * 2];
- int num = 0;
- while ((num = fis.read(buf)) != -1) {
- fos.write(buf, 0, num);
- }
- fos.close();
- fis.close();
- }
-
-
- private File replaceFile(File f) {
-
- String path = f.getAbsolutePath();
-
- String newPath = path.replace(sDir.getAbsolutePath(), newDir
- .getAbsolutePath());
-
- File newFile = new File(newPath);
- return newFile;
- }
- }