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){
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);
}
}