本文共 2035 字,大约阅读时间需要 6 分钟。
import java.io.*;
/**
* Created by IntelliJ IDEA.
* User: zl420226
* Date: 2010-4-10
* Time: 13:58:23
* To change this template use File | Settings | File Templates.
*/
public class ReplaceText {
public static void main(String[] args)
{try {
BufferedReader buff = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Source Folder path:");
System.out.flush();
String folderPath = buff.readLine();
BufferedReader buffTarget = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("target Folder path:");
System.out.flush();
String targetFolder = buffTarget.readLine();
BufferedReader buffSourceText = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("The content you will replace:");
System.out.flush();
String source = buffSourceText.readLine();
BufferedReader buffTargetText = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("replace as:");
System.out.flush();
String target = buffTargetText.readLine();
File file = new File(folderPath);
if(file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
{
BufferedReader bf = new BufferedReader(new FileReader(folderPath+"//"+filelist[i]));
BufferedWriter bw = new BufferedWriter(new FileWriter(targetFolder+"//"+filelist[i]));
String s = null;
while( (s = bf.readLine()) != null) {
s = s.replaceAll(source,target);
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
网络摘录:
知道你有无注意到,JDK中的String的ReplaceAll方法支持的是正则表达式,在你的参数中可能出现正则表达式转义符的情况下,很可能 得到意想不到的结果.所以做一个自己的ReplaceAll方法还是一个很有必要的工作.
public static String replaceAll(String src, String fnd, String rep) {
int pos = 0;
int prepos = 0;
int fndlen = fnd.length();
String newstr = "";
pos = src.indexOf(fnd, pos);
while (pos >= 0) {
newstr += src.substring(prepos, pos);
newstr += rep;
prepos = pos + fndlen;
pos = src.indexOf(fnd, pos + fndlen);
}
newstr += src.substring(prepos);
return newstr;
}
转载地址:http://uqlyo.baihongyu.com/