import java.io.*;
import java.util.*;
public class MoveFile{
private static ArrayList<File> al = new ArrayList<File>();
public static void main(String[] args) {
//将F:/java目录下的*。java文件和*。txt文件拷贝到F:/move目录下
moveFile("F:\\java", "F:\\move");
}
//将文件移动到指定的目录下
public static void moveFile(String src, String goal){
ArrayList<File> files = getFile(src);
BufferedReader bufr = null;
BufferedWriter bufw = null;
for(File file : files){
try {
bufr = new BufferedReader(new FileReader(file));
File f = new File(goal + "\\" + file.getName());
if(!f.exists())
f.createNewFile();
bufw = new BufferedWriter(new FileWriter(f));
String line = null;
while((line = bufr.readLine()) != null){
bufw.write(line);
bufw.newLine();
bufw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new RuntimeException("未找到源文件");
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException("拷贝失败");
}finally{
try {
if(bufw != null)
bufw.close();
if(bufr != null)
bufr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException("流资源关闭失败");
}
}
}
}
//获取一个目录下所有的文件和子文件,并且文件是*.java文件或者是*.txt文件
public static ArrayList<File> getFile(String src){
File f = new File(src);
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String fileName = file.getName();
if(fileName.endsWith(".java") || fileName.endsWith(".txt")){
al.add(file);
}
}else
if(file.isDirectory()){
getFile(file.getAbsolutePath());
}
}
return al;
}
} |