本帖最后由 王靖远 于 2013-6-19 21:20 编辑
import java.io.*;
import java.util.*;
/*
* 需求:编写一个程序,将d:\java 目录下的所有.java 文件复制到d:\jad 目录下,并将原来文件的扩展名从.java 改为.jad。
*把毕老师的第二十天视频中的JavaFileList.java代码稍作修改就可以完成这个需求了。有看不懂的地方可以回帖再问
* */
public class MoveFile
{
public static void fileToList(File dir,List<File> list)
{
File[] files = dir.listFiles();
for(File file : files)
{
if(file.isDirectory())
fileToList(file,list);
else
{
if(file.getName().endsWith(".java"))
list.add(file);
}
}
}
public static void moveFile(File dir,List<File>list)
{
String path =null;
File file = null;
BufferedWriter bufw = null;
BufferedReader bufr = null;
for(File f :list)
{
path = f.getPath();
path = path.replace("d:\\java", "d:\\jad");
System.out.println(path);
path = path.replace(".java",".jad");
System.out.println(path);
if(!dir.isDirectory())
dir.mkdir();
file = new File(path);
try
{
bufw = new BufferedWriter(new FileWriter(file));
bufr = new BufferedReader(new FileReader(f));
String line = null;
while((line=bufr.readLine())!=null)
{
bufw.write(line);
bufw.newLine();
bufw.flush();
}
}
catch(IOException e)
{
throw new RuntimeException("写入出错");
}
finally
{
try
{
if(bufw!=null)
bufw.close();
}
catch(IOException e)
{
throw new RuntimeException("输出流关闭失败");
}
try
{
if(bufr!=null)
bufr.close();
}
catch(IOException e)
{
throw new RuntimeException("读取流关闭失败");
}
}
}
}
public static void main(String[] args)
{
File dir1 = new File("d:\\java");
List<File>list = new ArrayList<File>();
fileToList(dir1,list);
File dir2 = new File("d:\\jad");
moveFile(dir2,list);
}
}
|