原生Java代码拷贝目录

时间:2022-06-14 01:24:37

拷贝、移动文件(夹),有三方包commons-io可以用,但是有时候有自己的需求,只能使用原生java代码,这时可以用以下几种方式进行拷贝:

1、使用系统命令(Linux)调用

此种方式对操作系统有要求,好处是代码量少,性能可依赖操作系统优化,但是中间环节不可控。

     /**
* 执行命令
*/
private static void nativeCall(String... cmd) {
ProcessBuilder pb = new ProcessBuilder(cmd);
try {
pb.redirectErrorStream(true);
Process process = pb.start();
InputStream stream = process.getInputStream();
byte[] buff = new byte[4096];
while (stream.read(buff, 0, 4096) != -1) {}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
} // 使用CMD拷贝目录
public static void cmdCopyDir(File src, File des) {
if (!des.exists()) {
des.mkdirs();
}
String[] cmds = new String[] { "sh", "-c", "cp -a \"" + src.getAbsolutePath() + "/.\" \"" + des.getAbsolutePath() + "\"" };
Executor.nativeCall(cmds);
} // 使用CMD删除目录
public static void cmdDelDir(File dic) {
if (dic.exists() && dic.isDirectory()) { // 判断是文件还是目录
String[] cmds = new String[] { "sh", "-c", "rm -rf \"" + dic.getAbsolutePath() + "\"" };
Executor.nativeCall(cmds);
}
}

2、使用文件通道拷贝

此种方式是常用的拷贝方式,大部分环节、异常都是可控的,具体的文件复制则使用了通道的方式进行加速。

     // 拷贝目录
public static void javaCopyDir(File src, File des) throws IOException {
if (!des.exists()) {
des.mkdirs();
}
File[] file = src.listFiles();
for (int i = 0; i < file.length; ++i) {
if (file[i].isFile()) {
channelCopy(file[i], new File(des.getPath() + "/" + file[i].getName()));
} else if (file[i].isDirectory()) {
javaCopyDir(file[i], new File(des.getPath() + "/" + file[i].getName()), stoppable);
}
}
} // 拷贝文件
private static void channelCopy(File src, File des) throws IOException {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
IOException ex = null;
try {
fi = new FileInputStream(src);
fo = new FileOutputStream(des);
in = fi.getChannel();
out = fo.getChannel();
in.transferTo(0, in.size(), out); // 连接两个通道,并且从in通道读取,然后写入out通道
} finally {
try {
fi.close();
in.close();
} catch (IOException e) {
ex = e;
}
try {
fo.close();
out.close();
} catch (IOException e) {
ex = e;
}
}
if (ex != null) {
throw ex;
}
}

3、原生删除目录

     // 删除目录
private static void javaDelDir(File dic) throws IOException {
if (dic.exists() && dic.isDirectory()) {
File delFile[] = dic.listFiles();
if (delFile.length == 0) { // 若目录下没有文件则直接删除
dic.delete();
} else {
for (File file : delFile) {
if (file.isDirectory()) {
javaDelDir(file); // 递归调用del方法并取得子目录路径
}
file.delete(); // 删除文件
}
dic.delete();
}
}
}

转载请注明原址:http://www.cnblogs.com/lekko/p/8472353.html