我正在使用java编写带有注释的文本文件的脚本。在评论中,我的sql脚本被编写。我正在评论 actions starts
和 actions ends
中编写我的脚本,我希望稍后将此注释中的脚本替换为其他一些脚本。 如何删除指定评论中可用的脚本和添加新脚本。
--
-- `actions` starts
--
CREATE TABLE IF NOT EXISTS `actions` (
`aid` varchar(255) NOT NULL DEFAULT '0' COMMENT 'Primary Key: Unique actions ID.',
`type` varchar(32) NOT NULL DEFAULT '' COMMENT 'The object acts on ',
PRIMARY KEY (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores action.';
--
-- `actions` ends
--
--
-- `operations` starts
--
CREATE TABLE IF NOT EXISTS `operations` (
`type` varchar(32) NOT NULL DEFAULT '' COMMENT 'The object that that action acts on ',
`callback` varchar(255) NOT NULL DEFAULT '' COMMENT 'The callback ',
`parameters` longblob NOT NULL COMMENT 'Parameters to be passed to .',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores operations.';
--
-- `operations` ends
--
答案 0 :(得分:0)
我找到了解决方案。解决方案是使用 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); 标识结束标记。
它将找到该块并将用新的内容替换该内容。