.txtファイル内の単語(トランザクション番号)のリストを検索するプログラムをJavaで作成しています。.txtファイルには任意の数の行を含めることができます。
List<String> transactionList = new ArrayList<String>(
Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037");
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
String readLine = bufferedReader.readLine();
for (String transactionIndex : transactionList) {
if (readLine != null) {
if (readLine.contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
readLine = bufferedReader.readLine();
} else {
readLine = bufferedReader.readLine();
}
}
}
}
単語が2行に分割されている場合を除いて、プログラムは正常に実行されます。次に例を示します。
-------- JQ7P0
0049 ----------
これは明らかに、bufferedReaderが行ごとに読み取り、検索文字列とその行に存在するコンテンツとの比較を行うためです。
このシナリオを処理する方法はありますか?
durron597が述べたように、ファイル全体をループしていませんでしたが、ファイルに少なくとも2行があり、トランザクション文字列が2行を超えないことを前提としたソリューションを次に示します。
各行を次の行に連結し、連結された行の文字列を検索します。同じトランザクションが2回印刷されるのを防ぐために、チェックを追加しました。
List<String> transactionList = new ArrayList<String>( Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037") );
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
// Search the first line
String lastLine = bufferedReader.readLine();
for (String transactionIndex : transactionList) {
if (lastLine.contains(transactionIndex)) {
System.out.println(transactionIndex + ": true");
}
}
String currentLine = null;
// Search the remaining lines
while((currentLine=bufferedReader.readLine()) != null) {
String combined = lastLine + currentLine;
for (String transactionIndex : transactionList) {
if (currentLine.contains(transactionIndex) || (!lastLine.contains(transactionIndex) && combined.contains(transactionIndex))) {
System.out.println(transactionIndex + ": true");
}
}
lastLine = currentLine;
}
} catch ( Exception e ) {
System.out.println( e.getClass().getSimpleName() + ": " + e.getMessage() );
} finally {
bufferedReader.close();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加