需求:复制多级文件夹
数据源:E:/Shadowsocks-win-2.5.2/test2目的地:E:将该多级文件夹整个复制到e盘根目录
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Administrator
*
*/
public class Java_2
{
public static void main(String[] args)
{
File file =
new File(
"E:\\Shadowsocks-win-2.5.2\\test2");
File file2 =
new File(
"E:");
findFiles(file, file2);
}
/**
* 判断多级文件夹文件并复制的方法
* @param file
* @param file2
*/
public static void findFiles(File file, File file2)
{
if (file.exists())
{
if (file.isFile())
{
copyFiles(file, file2);
System.out.println(file.getAbsolutePath() +
"已创建");
}
else if (file.isDirectory())
{
File file5 =
new File(file2.getAbsolutePath() +
"\\"
+ file.getName());
file5.mkdirs();
File[] file3 = file.listFiles();
if (file3 ==
null)
{
return;
}
for (File file4 : file3)
{
findFiles(file4, file5);
System.out.println(file5.getAbsolutePath() +
"已创建");
}
}
}
else
{
return;
}
}
/**
* 把file的内容复制到file2的方法
* @param file
* @param file2
*/
public static void copyFiles(File file, File file2)
{
FileInputStream fis;
FileOutputStream fos;
BufferedInputStream bis =
null;
BufferedOutputStream bos =
null;
try
{
fis =
new FileInputStream(file);
fos =
new FileOutputStream(file2.getAbsolutePath() +
"\\"
+ file.getName());
bis =
new BufferedInputStream(fis);
bos =
new BufferedOutputStream(fos,
10 *
1024 *
1024);
byte[] bytes =
new byte[
1024];
int len =
0;
long start = System.currentTimeMillis();
while ((len = bis.read(bytes,
0,
1024)) != -
1)
{
bos.write(bytes,
0, len);
}
long end = System.currentTimeMillis();
System.out.println(
"复制" + file.getName() +
"花费时间" + (end - start)
+
"ms");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (bis !=
null)
{
try
{
bis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (bos !=
null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
输出结果:
复制RAR 压缩文件.rar 花费时间0ms
E:
\Shadowsocks-win-2.5.2
\test2
\RAR 压缩文件.rar已创建
E:
\test2已创建
复制新建文本文档.avi 花费时间0ms
E:
\Shadowsocks-win-2.5.2
\test2
\tstst\新建文本文档.avi已创建
E:
\test2
\tstst已创建
复制肖4配套视频.flv 花费时间1330ms
E:
\Shadowsocks-win-2.5.2
\test2
\tstst\肖4配套视频.flv已创建
E:
\test2
\tstst已创建
复制酬勤考资全自动播放器.exe 花费时间33ms
E:
\Shadowsocks-win-2.5.2
\test2
\tstst\酬勤考资全自动播放器.exe已创建
E:
\test2
\tstst已创建
E:
\test2已创建
复制新建位图图像.bmp 花费时间0ms
E:
\Shadowsocks-win-2.5.2
\test2
\新建位图图像.bmp已创建
E:
\test2已创建
转载请注明原文地址: https://ju.6miu.com/read-6581.html