上一篇写的是将内容写入新文件,读完后删除源文件,在修改新文件名。
本次用的方法是创建随机文件流,用来读取源文件内容,找到第一次包含目标字符串内容的位置,然后将目标字符串替换写入临时文件,后面不包含目标字符串的内容也写入,含目标字符串则替换写入。读取完源文件后,将随机文件流定位回记录的位置,最后将临时文件内容写入,删除临时文件。即达到替换文本内容的效果。
oldString 目标字符串
newString替换字符串
newFile临时文件
以下为代码实现过程:
public class AlterStringInFile {
private static String path ="src/源文件"; //目标文件路径
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 = "oldString";
String newString = "newString";
alterStringInNewFileReturnFile(oldString,newString);
}
}
源文件内容为本次代码内容,以下为运行结果: