——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
利用IO流复制windows下的一个多级文件夹
1.目录下包含文件和文件夹
2.判断目录下的内容,如果是文件,就创建并拷贝,如果是文件夹,就创建。用递归实现。
例如我想把E盘下的eclipse文件夹复制到D盘
eclipse文件夹里有文件和文件夹,文件夹里还有文件和文件夹
import java.io.*;
public class Copy {
public static void main(String[] args) {
File source = new File("E:\eclipse");
File target = new File("D:");
copyDir(source,target);
}
public static void copyDir(File source,File target){
//判断目录下是文件夹
//创建新目录
if(source.isDirectory()){
File dir = new File(target,source.getName());
//在target下建立同名目录
dir.mkdirs();
//遍历source下的所有子目录,将每个文件作为source,将新创建的目录作为target进行递归
File[] files = source.listFiles();
for(File file:files){
copyDir(file,dir);
}
}else{//是文件,就在目录下创建同名文件,并用流操作实现文件拷贝
File file = new File(target,source.getName());
copyFile(source,file);
}
}
//拷贝文件
public static void copyFile(File source,File file){
//创建流对象
InputStream is = null;
OutputStream os = null;
try{
is = new FileInputStream(source);
os = new FileOutputStream(file);
//读写基本操作
byte[] bytes = new byte[1024];
int len = 0;
while((len = is.read(bytes))!= -1){
os.write(bytes, 0, len);
}
}catch(IOException e){
throw new RuntimeException("复制文件失败");
}finally{
try{
if(os!=null)
os.close();
}catch(IOException e){
throw new RuntimeException("关闭资源失败");
}finally{
try{
if(is!=null)
is.close();
}catch(IOException e){
throw new RuntimeException("关闭资源失败");
}
}
}
}
}
用IO流复制文件的速度比windows快,这里我创建的数组是1M的
不知道如果byte[] bytes = new byte[1024*10]的话会不会更快呢?
在复制大文件和文件夹上确实比windows快,所以当然要做一个工具类,以后拷大文件和文件夹就可以直接用啦