【发布时间】:2015-06-08 08:51:56
【问题描述】:
我有一个文件,其中包含一个带有 cmets 的标题(例如 [Comment] 这是一个注释)和一个后续数据部分。数据从“Mk1=”开始。
我正在开发的程序应该:
- 复制标题内容
- 仅在文件的数据部分搜索和替换
- 将标头和数据写入新文件
我目前正在使用:
- 字符串缓冲区
- 扫描仪
- 正则表达式.模式;
到目前为止,在我的代码中(简化为基本内容):
public static void main(String[] args) {
File file = readFile("file.ext");
Scanner inputScanner = null;
try {
inputScanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine = "";
while(inputScanner.hasNext()) {
currentLine = inputScanner.findInLine(regexpPattern);
if (currentLine != null){
fileOutput.append(currentLine + "\n");
}
}
}
由于扫描器的工作方式类似于队列,我无法确定应该使用什么策略。我找到了使用 Matcher 而不是 Scanner 的示例。据我了解,由于 Scanner 具有类似队列的结构,我还必须使用布尔标志。 findInHorizon() 方法似乎没有帮助,因为我希望 reg exp 仅适用于地平线之外。假设我知道标题开始和结束的一系列字符,扫描仪的分隔符是否可能存在“hack”?
文件示例
[Comment]
Text goes here.
[Another Comment]
;Instructions: Below you will find Mk1= where the data can be assigned.
;More text.
Mk1=data
Mk2=data
Mk3=data
我应该使用什么策略?
【问题讨论】: