最も効率的な方法は、ファイルの読み取り中に開始文字列と終了文字列を置き換える 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,"\"@@","");