我有一个文件,其中包含带注释的标题(例如[Comment]这是一个注释)和后续的数据部分。数据从“Mk1 =”开始。在Java中使用Reg Exp处理文本文件的策略
程序我的工作应该:
- 复制标题内容
- 搜索并仅在文件
- 写头和数据的数据部分替换为新的文件
我目前使用的是:
- 的StringBuffer
- 扫描器
- regex.Pattern;
在我的代码到目前为止(减少其要领):
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的例子。据我的理解,我也必须使用布尔标志,因为扫描器的队列结构。 findInHorizon()方法似乎并不有用,因为我希望reg exp仅适用于超出地平线的范围。假设我知道标题开始和结束的一系列字符,是否有可能是扫描器分隔符的“黑客”?
文件示例
[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
我应该使用什么策略?
这看起来很有希望。这些文件大约是31 kB。在每个文件之后关闭InputStream足够了吗? – noumenal
@noumenal我肯定会考虑31 kB的小文件。无需打开或关闭任何文件流,即使出现错误,Files.readAllLines()方法也可以处理文件的打开和关闭,这是一种非常高级的方法,适用于您的任务。它可能会在找不到文件时抛出一个'IOException'。 –