最有效的方法是编写一个 FilterReader 在您读取文件时替换开始和结束字符串。我认为不需要正则表达式来替换静态数据。以下代码可以解决问题:
public class ReplaceFilterReader extends Reader {
private String match;
private String replace;
private BufferedReader in;
private boolean matched;
private int currentPos;
private boolean end = false;
public ReplaceFilterReader(Reader in, String match, String replace) {
this.in = new BufferedReader(in);
this.matched = false;
this.currentPos = 0;
this.match = match;
this.replace = replace;
}
@Override
public int read(CharBuffer target) throws IOException {
int len = target.remaining();
char[] cbuf = new char[len];
int n = read(cbuf, 0, len);
if (n > 0) {
target.put(cbuf, 0, n);
}
return n;
}
@Override
public int read(char[] cbuf) throws IOException {
return this.read(cbuf, 0, cbuf.length);
}
@Override
public int read() throws IOException {
char cb[] = new char[1];
if (this.read(cb, 0, 1) == -1) {
return -1;
} else {
return cb[0];
}
}
private int readNext() throws IOException {
int result = 0;
if (!matched) {
this.in.mark(match.length());
char cb[] = new char[match.length()];
int n = this.in.read(cb);
if (n>0) {
String s = new String(cb);
if (s.equals(match)) {
this.matched = true;
if (replace.length()>0) {
result = replace.charAt(currentPos);
currentPos+=1;
if (currentPos == replace.length()) {
this.matched = false;
this.currentPos = 0;
}
} else {
this.matched = false;
this.currentPos = 0;
result = 0;
}
} else {
this.in.reset();
result = this.in.read();
}
} else {
result = n;
}
} else {
result = replace.charAt(currentPos);
currentPos+=1;
if (currentPos == replace.length()) {
this.matched = false;
this.currentPos = 0;
}
}
return result;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if (end) {
return -1;
}
int n = 0;
int read = 0;
for (int i=0; i<len && n!=-1; i++) {
n = this.readNext();
if (n!=-1 && n!=0) {
read += 1;
cbuf[off+i] = (char) n;
} else if (n==0) {
i = i-1;
}
}
if (n == -1) {
end = true;
}
return read;
}
@Override
public void close() throws IOException {
this.in.close();
}
}
你会这样进行:
Reader yourReader = // open file ...
Reader replaceStart = new ReplaceFilterReader(yourReader,"@@GOTO:\"","");
Reader replaceEnd = new ReplaceFilterReader(replaceStart,"\"@@","");