我正在用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();
}
关于java - 如何搜索分成两行的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144200/