我正在用Java编写程序,以搜索.txt文件中的单词(事务编号)列表。.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();
}
}
}
}
程序运行正常,除非单词被分为两行,例如:
-------- JQ7P0
0049 ----------
这显然是因为bufferedReader逐行读取并将搜索字符串与该行中存在的内容进行比较。
有什么办法可以处理这种情况?
正如durron597所提到的,您并没有遍历整个文件,但是这里的解决方案假定文件至少有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] 删除。
我来说两句