您的位置:首页 > 编程语言 > Java开发

Java 拷贝文件及目录

2015-08-23 22:58 357 查看
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFolder {

/**
* 拷贝文件
* @param sourcefile
* @param targetFile
* @throws IOException
*/
public static void copyFile(File sourcefile,File targetFile) throws IOException{
//新建文件输入流并对它进行缓冲
FileInputStream input=new FileInputStream(sourcefile);
BufferedInputStream inbuff=new BufferedInputStream(input);
//新建文件输出流并对它进行缓冲
FileOutputStream out=new FileOutputStream(targetFile);
BufferedOutputStream outbuff=new BufferedOutputStream(out);
//缓冲数组
byte[] b=new byte[1024*5];
int len=0;
while((len=inbuff.read(b))!=-1){
outbuff.write(b, 0, len);
}
//刷新此缓冲的输出流
outbuff.flush();
//关闭流
inbuff.close();
outbuff.close();
out.close();
input.close();
}

/**
* 拷贝文件夹
* @param sourceDir
* @param targetDir
* @throws IOException
*/
public static void copyDirectiory(String sourceDir,String targetDir) throws IOException{

File target = new File(targetDir);
if(!target.exists()){
//新建目标目录
target.mkdirs();
}
//获取源文件夹当下的文件或目录
File[] file=(new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if(file[i].isFile()){
//源文件
File sourceFile=file[i];
//目标文件
File targetFile=new File(new File(targetDir).getAbsolutePath()+File.separator+file[i].getName());
copyFile(sourceFile, targetFile);
}

if(file[i].isDirectory()){
//准备复制的源文件夹
String dir1=sourceDir+file[i].getName();
//准备复制的目标文件夹
String dir2=targetDir+"/"+file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}

public static void main(String[] args){
//源文件夹
String sourceFolder = "D:/test";
//目标文件夹
String targetFolder = "D:/test1";

CopyFolder copy = new CopyFolder();

File f = new File("/");
String path = f.getClass().getResource("/").getPath();
path = path.substring(1,path.length());
try {
copy.copyDirectiory(sourceFolder, path+"imgPath");
} catch (IOException e) {
e.printStackTrace();
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: