解決策を見つけました。解決策は、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);を識別します。終了タグを識別します。
ブロックを見つけて、コンテンツを新しいものに置き換えます。