本帖最后由 当我遇上你 于 2015-1-14 20:37 编辑
package com.itheima;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
public class Copy1 {
public static void main(String[] args) throws IOException {
File src = new File("D:\\A");
File dest=new File("D:\\B");
copyDir(src,dest);
}
public static void copyDir(File src,File dest) throws IOException
{
if(!dest.exists())
{
System.out.println("目录不存在,新建一个");
dest.mkdirs();
}
File[] files=src.listFiles(/*new FilenameFilter() { //这里不能写过滤器,否则会直接滤掉子目录
@Override
public boolean accept(File dir, String name) {
File currfile = new File(dir,name);
if(currfile.isFile()&&name.endsWith(".java"))
return true;
return false;
}
}*/);
//实现文件夹复制
for(File file:files)
{
if(file.isDirectory())
{
copyDir(file, new File(dest.getAbsolutePath()+"\\"+file.getName()) );
}
else
{
if(file.getName().endsWith(".java"))
{
copyFile(file,new File(dest.getAbsolutePath()+"\\"+file.getName()));
}
}
}
}
//实现文件复制
private static void copyFile(File src, File dest) throws IOException{
BufferedReader bfr = new BufferedReader(new FileReader(src));
BufferedWriter bfw = new BufferedWriter(new FileWriter(dest.getAbsolutePath().replace(".java", ".txt")));
String str;
while((str=bfr.readLine())!=null)
{
bfw.write(str);
}
bfr.close();
bfw.flush();
bfw.close();
}
}
1、在复制时把后缀改为.txt格式
2、实现复制后改后缀.txt:
|