我有一個文件,其中包含帶註釋的標題(例如[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'。 –