0

嗨,我正在尝试添加一个功能,我还可以在其中跟踪找到的字符串的行号。不知道在下面的代码中在哪里以及如何实现它。请记住,我正在查看的文件大小为 50mb。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class scanFiles {
    private static void scanFiles(String folderPath, String searchString) throws FileNotFoundException, IOException {
        File folder = new File(folderPath);

        if (folder.isDirectory()) {
            for (File file : folder.listFiles()) {
                if (!file.isDirectory()) {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String content = "";
                    try {
                        StringBuilder sb = new StringBuilder();
                        String line = br.readLine();

                        while (line != null) {
                            sb.append(line);
                            sb.append(System.lineSeparator());
                            line = br.readLine();
                        }
                        content = sb.toString();


                    } finally {
                        br.close();
                    }
                    if (content.contains(searchString)) {
                        System.out.println("File " + file.getName() + " contains searchString " + searchString + "!");
                    }

                }
            }
        } else {
            System.out.println("Not a Directory!");
        }
    }
    public static void main(String args[]) throws FileNotFoundException, IOException{
        scanFiles(new File("C://Users//FarmaniA//Documents//COB NAK Messages").getAbsolutePath(),"15:09:07,803");

}
}
4

1 回答 1

2

阅读时在文件的每一行上循环搜索文本。记录找到字符串的行号。例如:

List<Integer> lineNumbers = new ArrayList<Integer>();
int lineNumber = 0;
while ( line != null ){
    lineNumber++;
    if ( line.indexOf(searchString) != -1 ){
        lineNumbers.add(lineNumber);
    }
    line = br.readLine();
}
if ( lineNumbers.size() > 0 ){
    //do something with them
}

根据上下文,您可能还希望通过将搜索字符串和每一行更改为特定大小写(大写/小写)来进行不区分大小写的搜索。

于 2015-03-31T18:44:52.220 回答