本帖最后由 凝聚 于 2013-12-25 11:03 编辑
我想修改一个文件夹中的所有指定扩展名的文件中的部分内容,并把修改后的文件保存到指定的文件夹中(如D:\\新建文件夹\\下的若干个java文件中的内容)下面是我的代码,但不能实现啊请大伙指教。
package xiugai;
import java.io.*;
import java.util.*;
public class zuhe {
public static File cfile()
{
File file=null;
System.out.println("请输入文件所在的路径");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String path=null;
try {
path = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// String path = "D:\\File\\workspace\\heima\\src\\fourteen";
File root = new File(path);
//判断路径
if(! root.exists() && root.isDirectory()){
System.out.println("路径有误!");
}
File[] files = root.listFiles(
new FilenameFilter(){
//文件名称过滤
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
}
);
na(files);
/*
for(File file : files){
String Name = file.getName();
System.out.println(Name);
}
*/
return file;
}
public static void gaiFile(File file)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file.getName()))); //传入指定文件夹下的所有文件名。
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\File\\workspace\\heima\\src\\ninee")));
StringBuilder sb=new StringBuilder();
String line;
try {
while((line=br.readLine())!=null){
sb.append(line);
int index=0;
while((index=sb.indexOf("ii",index))!=-1){
sb.replace(index,index+"ii".length(),"oo");
index+="oo".length();
}
bw.write(sb.toString(),0,sb.length());
bw.newLine();
sb.delete(0,sb.length());
}
} catch (IOException e) {
e.printStackTrace();
}
br.close();
bw.flush();
bw.close();
}
public static void na(File[] files )
{
for(File file : files)
{
String Name = file.getName();
System.out.println(Name);
}
}
public static void main(String[] args)throws Exception {
gaiFile( cfile());
}
}
|