我找到了解决方案。解决方案是使用indexOf方法来识别起始块和结束块。我使用的代码是,
private static final String VARIABLE_FIELD = "variable";
private static final String END_MODULE_END_TAG = "' ends";
private static final String START_MODULE_END_TAG = "' starts";
private static final String MODULE_START_TAG = "-- '";
private static final String DOUBLE_HYPHEN = "--";
private static final String VALUE_FIELD = "value";
private static final String NAME_FIELD = "name";
private static final String SQL_VARIABLE_SEP = "`,`";
private static final String SQL_VALUE_SEP = "','";
private static final String SINGLE_QUOTE = "'";
private static final String LINE_BREAK = "\n";
private static final String EQUAL = "=";
File scriptFile = new File(versionFile + File.separator + fileName);
StringBuffer sb = new StringBuffer();
if (scriptFile.isFile()) {
// if script file is available need to replace the content
buff = new BufferedReader(new FileReader(scriptFile));
String readBuff = buff.readLine();
String sectionStarts = MODULE_START_TAG + moduleName + START_MODULE_END_TAG;
String sectionEnds = MODULE_START_TAG + moduleName + END_MODULE_END_TAG;
while (readBuff != null) {
sb.append(readBuff);
sb.append(LINE_BREAK);
readBuff = buff.readLine();
}
int cnt1 = sb.indexOf(sectionStarts);
int cnt2 = sb.indexOf(sectionEnds);
if (cnt1 != -1 || cnt2 != -1) {
sb.replace(cnt1 + sectionStarts.length(), cnt2, LINE_BREAK + queryString + LINE_BREAK);
} else {
// if this module is not added already in the file and need to add this config alone
sb.append(LINE_BREAK + DOUBLE_HYPHEN + LINE_BREAK);
sb.append(MODULE_START_TAG + moduleName + START_MODULE_END_TAG + LINE_BREAK);
sb.append(queryString);
sb.append(LINE_BREAK);
sb.append(MODULE_START_TAG + moduleName + END_MODULE_END_TAG + LINE_BREAK);
sb.append(DOUBLE_HYPHEN + LINE_BREAK);
}
}
关键代码是
int cnt1 = sb.indexOf(sectionStarts); int cnt2 = sb.indexOf(sectionEnds); if (cnt1 != -1 || cnt2 != -1) { sb.replace(cnt1 + sectionStarts.length(), cnt2, LINE_BREAK + queryString + LINE_BREAK); }
int cnt1 = sb.indexOf(sectionStarts); 它标识起始标签和int cnt2 = sb.indexOf(sectionEnds); 标识结束标签。
它将找到该块并将内容替换为新内容。