在文本文件中查找字符串的方法。然后将以下行提升到一定限度

2022-09-01 14:55:13

这就是我到目前为止所拥有的:

public String[] findStudentInfo(String studentNumber) {
                Student student = new Student();
                Scanner scanner = new Scanner("Student.txt");
                // Find the line that contains student Id
                // If not found keep on going through the file
                // If it finds it stop
                // Call parseStudentInfoFromLine get the number of courses
                // Create an array (lines) of size of the number of courses plus one
                // assign the line that the student Id was found to the first index value of the array
                //assign each next line to the following index of the array up to the amount of classes - 1
                // return string array
}

我知道如何查找文件是否包含我试图查找的字符串,但我不知道如何检索其所在的整行。

这是我第一次发帖,所以如果我做错了什么,请让我知道。


答案 1

你可以做这样的事情:

File file = new File("Student.txt");

try {
    Scanner scanner = new Scanner(file);

    //now read the file line by line...
    int lineNum = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        lineNum++;
        if(<some condition is met for the line>) { 
            System.out.println("ho hum, i found it on line " +lineNum);
        }
    }
} catch(FileNotFoundException e) { 
    //handle this
}

答案 2

使用Apache Commons IO API https://commons.apache.org/proper/commons-io/ 我能够使用以下命令建立它FileUtils.readFileToString(file).contains(stringToFind)

此函数的文档位于 https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)