在文本文件中查找字符串的方法.然后让以下几行达到一定的限制 [英] Method to find string inside of the text file. Then getting the following lines up to a certain limit

查看:11
本文介绍了在文本文件中查找字符串的方法.然后让以下几行达到一定的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我目前所拥有的:

So this is what I have so far :

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
}

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

I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.

这是我第一次发帖,如果我做错了什么,请告诉我.

This is my first time posting so If I have done anything wrong please let me know.

推荐答案

你可以这样做:

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
}

这篇关于在文本文件中查找字符串的方法.然后让以下几行达到一定的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆