Java实现替换文本内容(转载)
import java.io.*;
public class replace {
//目标文件路径
private static String path ="D:\\workplace\\data\\replaceSpace\\scsmcs.sql";
//创建目标文件
private static File file = new File(path);
public static void alterStringInNewFileReturnFile(String oldString,
String newString){
try {
long start = System.currentTimeMillis();
//创建临时文件
File newFile = new File("src/临时文件");
if(!newFile.exists()){
newFile.createNewFile();
}
//创建随机文件流
RandomAccessFile raf = new RandomAccessFile(file, "rw");
//创建对临时文件缓存输出流
BufferedWriter bw_NewFile = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(newFile,true)));
String string ; //存储读取内容
long lastPoint = raf.getFilePointer(); //记录每次读取位置
long point = 0; //记录第一次包含目标字符串位置
int sum = 0; //记录包含目标字符串次数
boolean flag = false; //判断是否是目标字符之后内容
while ((string = raf.readLine()) != null){
//随机文件流读取的时候会将GBK格式转为ISO-8859-1,
//将读取的内容转回本地格式
string = new String(string.getBytes("ISO-8859-1"));
//判断是否包含目标字符
if(string.contains(oldString)){
if(sum == 0)
point = lastPoint;
string = new String(
string.replace(oldString, newString));
bw_NewFile.write(string);
bw_NewFile.newLine();
sum++;
flag = true;
} else if (flag){
bw_NewFile.write(string);
bw_NewFile.newLine();
} else {
lastPoint = raf.getFilePointer();
}
}
bw_NewFile.close();
BufferedReader br_NewFile = new BufferedReader(
new InputStreamReader(
new FileInputStream(newFile)));
raf.seek(point);
while((string = br_NewFile.readLine()) != null){
string = string +"\r\n";
raf.write(string.getBytes());
}
br_NewFile.close();
raf.close();
newFile.delete();
long time = System.currentTimeMillis() - start;
System.out.println(sum+"个"+oldString
+"替换成"+newString+"耗费时间:"+time);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
String oldString ;
String newString ;
oldString = "/*END*/";
newString = "/*%end*/";
alterStringInNewFileReturnFile(oldString,newString);
oldString = "/*IF";
newString = "/*%if*/";
alterStringInNewFileReturnFile(oldString,newString);
oldString = "dto.eikbn";
newString = "/*dto.getForm().getEikbn()*/";
alterStringInNewFileReturnFile(oldString,newString);
oldString = "/*dto.key1*/";
newString = "/*dto.geyKey1()*/";
alterStringInNewFileReturnFile(oldString,newString);
oldString = "/*dto.where1*/";
newString = "/*dto.getWhere1()*/";
alterStringInNewFileReturnFile(oldString,newString);
}
}