这个方法有个BUG,文本文件会在文件夹外创建,如果有人知道咋回事 可以指点一下,谢谢。
package IO;
import java.io.*;
public class CopyAll {
public static void main(String[] args) {
//调用copy方法
copy("D:\\笔记\\mu","C:\\"); // D:\\==D:/
System.out.println("复制完成!");
}
private static void copy(String f1, String f2) {
//源文件
File file1 = new File(f1);
File[] files =file1.listFiles();
//循环
for (File f:
files) {
//判断是一个文件夹么?
if(f.isDirectory()){
copyDirectory(f.getAbsolutePath(),(f2.endsWith("\\")?f2:f2+"\\")+f.getAbsolutePath().substring(3));
// destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3);
System.out.println("原路径-"+f.getPath());
System.out.println("复制路径-"+(f2.endsWith("\\")?f2:f2+"\\")+f.getName());
}else if (f.isFile()){ //判断源文件是一个文件么?
//需要判断文件的结尾
//copyFile(f.getPath(),f2+f.getName());
//改写
System.out.println("测试"+f.getName());
copyFile(f.getAbsolutePath(),(f2.endsWith("\\")?f2:f2+"\\")+f.getName());
System.out.println("原路径-"+f.getAbsolutePath());
System.out.println("复制路径-"+(f2.endsWith("\\")?f2:f2+"\\")+f.getName());
//(f2.endsWith("\\")?f2:f2+"\\")+f.getName()
}
}
}
/**
* 复制文件夹方法
* @param f1
* @param f2
*/
private static void copyDirectory(String f1,String f2) {
//创建文件夹
File file = new File(f2);
if(!file.exists()){
file.mkdirs();
}
copy(f1,f2);
}
/**
* 复制文件方法
* @param f1 源文件
* @param f2 目标文件
*/
private static void copyFile(String f1,String f2) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//源文件
fis = new FileInputStream(f1);
//拷贝文件
fos = new FileOutputStream(f2);
//一边读一边写
byte[] bytes = new byte[1024*1024];
int readCount = 0;
while ((readCount=fis.read(bytes))!=-1){
fos.write(bytes,0,readCount);
}
//flush输出流
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}