本例以Windows, JDK1.7 为基础,来演示使用Java 目录(文件夹)的拷贝。
目录的拷贝与文件拷贝不同之处是目录下面可能存在多个目录或者文件,所以需要多次创建目录和文件。
关于文件的拷贝: Java File Copy 文件的拷贝
目录的拷贝
FileCopyDirectory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package com.devnp.io;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
public class FileCopyDirectory {
public static void main(String[] args) { File src = new File("D:\\Person-Test\\temp\\2"); File dest = new File("D:\\Person-Test\\temp\\3"); copyDirectory(src, dest); }
public static void copyDirectory(File src, File dest) { if (src.isDirectory()) { if (!dest.exists()) { dest.mkdirs(); }
String files[] = src.list();
for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file);
copyDirectory(srcFile, destFile); } } else { copy(src, dest); } }
public static void copy(File src, File dest) { InputStream inStream = null; OutputStream outStream = null; try { inStream = new FileInputStream(src); outStream = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length; while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length); }
inStream.close(); outStream.close();
System.out.println("File is copied successful!");
} catch (IOException e) { e.printStackTrace(); } }
}
|
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE