黑马程序员技术交流社区
标题:
复制文件夹在第几天的哪个视频中将的
[打印本页]
作者:
kangxiaoning
时间:
2013-12-3 18:10
标题:
复制文件夹在第几天的哪个视频中将的
复制文件夹这个功能在第几天哪个视频中将的啊,急求
作者:
ysunday
时间:
2013-12-3 19:25
这个好像没有吧 我没看见过 不过粘了个代码过来 你咱们的一个版主写的
总体思想就是递归,要是目录就递归,要是文件就复制
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class CopyPath{
public static void main(String[] args)throws IOException{
String copyPathStr = "F:\\test"; //要复制的文件夹
String savePathStr = "F:\\copy"; //要保存到哪里
System.out.println("正在复制...");
copyPath(copyPathStr,savePathStr);
System.out.println("复制成功");
}
/**
* 复制文件夹,本例没有包含该文件夹,只复制该文件夹下的所有文件及文件夹。
* @param copyPathStr 要复制的文件夹
* @param savePathStr 要复制到哪个文件夹下
*/
public static void copyPath(String copyPathStr,String savePathStr){
//首先用接收到的两个字符串创建成文件对象
File copyPath = new File(copyPathStr);
File savePath = new File(savePathStr);
//判断保存的目录是否存在
if (!(copyPath.exists())){
System.out.println("保存的目录不是有效目录!");
return;
}
//判断在该目录下是否有相同的文件存在
if (savePath.exists()){
System.out.println("复制失败!文件夹重复");
return;
}
//创建主目录
savePath.mkdirs();
//获取该目录下所有文件及文件夹的数组列表
File[] files = copyPath.listFiles();
File pathStr = null;
for(File file : files){
//建立保存的目录
pathStr = new File(savePathStr+(file.toString().replace(copyPathStr, "")));
//如果是目录,再次调用fileToList方法。并创建目录
if(file.isDirectory()){
copyPath(file.toString(),pathStr.toString());
pathStr.mkdirs();
}
//如果是文件,就调用复制文件的方法
if(file.isFile()){
copyFile(file,pathStr);
}
}
}
/**
* 复制文件
* @param file 要复制的文件绝对路径
* @param path 要保存到的目录
*/
public static void copyFile(File file,File path){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
//若以上判断都通过,就创建输入流和输出流。
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(new FileOutputStream(path));
//创建数组,指定大小为available方法获取的读取流中的字节数。
byte[] bytes = new byte[bis.available()];
//保存数据
bis.read(bytes);
bos.write(bytes);
}catch(IOException e){
throw new RuntimeException("复制文件失败");
}
//关闭流资源
finally{
try{
if (bis!=null){
bis.close();
}
}catch(IOException e){
throw new RuntimeException("输入流关闭失败");
}
try{
if (bos!=null){
bos.close();
}
}catch(IOException e){
throw new RuntimeException("输出流关闭失败");
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2