标签:private package public 文件夹 import
package package1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy {
private static File newDest = null;
private static FileInputStream fis = null;
private static FileOutputStream fos = null;;
/*
* 拷贝一个多级文件夹,文件里包含音频和视频文件
*
* 1 因为源文件夹下包含各类文件,因此采用字节流读写
* 2 不仅仅要复制文件,还要复制源文件夹,这里用到File类的构造函数在目标文件夹下创建同名同级文件夹
* 3 这里要用到getName()方法来获取对应的文件夹或者文件名
*/
public static void main(String[] args) throws IOException {
// 源文件
File source = new File("C:\\java");
//创建一个同名的一级目录
File dest = new File("d:",source.getName());
//创建目标文件夹
if(!dest.exists())
dest.mkdir();
copyFile(source,dest);
}
public static void copyFile(File source,File dest) throws IOException{
File[] files = source.listFiles();
for(File file : files){
//每次遍历时,都要在目标文件夹下创建同名同级文件夹或者文件
newDest = new File(dest,file.getName());
//打印遍历到的文件或者文件夹
System.out.println(newDest);
if(file.isDirectory()){
//如果遍历到的是文件夹,就在目标文件夹下创建同名同级文件夹
if(!newDest.exists())
newDest.mkdir();
copyFile(file,newDest );
}
else{
//如果遍历到的是文件,就在目标文件夹下创建同名同级文件并写入
fis = new FileInputStream(file);
fos = new FileOutputStream(newDest);
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1){
fos.write(buf,0,len);
fos.flush();
}
fis.close();
fos.close();
}
}
}
}一个可以复制C盘名为“java”的文件夹到D盘的程序,
试了一些,真的不错,先留着,之后再自己实现一个。
标签:private package public 文件夹 import
原文地址:http://sesedese.blog.51cto.com/9595075/1585728