Подтвердить что ты не робот

Метод поиска строки внутри текстового файла. Затем, получив следующие строки до определенного предела

Так вот что я до сих пор:

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
}

Я знаю, как найти, содержит ли файл строку, которую я пытаюсь найти, но я не знаю, как получить всю строку, в которой она находится.

Это мой первый пост, поэтому, если я сделал что-то неправильно, сообщите мне.

4b9b3361

Ответ 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
}

Ответ 3

Когда вы читаете файл, считаете ли вы его прочтением по очереди? Это позволит вам проверить, содержит ли ваша строка файл, который вы читаете, и тогда вы можете выполнить любую логику, которая вам нужна, на основе этого?

Scanner scanner = new Scanner("Student.txt");
String currentLine;

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Perform logic
    }
}

Вы можете использовать переменную, чтобы удерживать номер строки, или вы также можете иметь логическое указание, если вы передали строку, содержащую вашу строку:

Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

Ответ 4

Вот метод java 8 для поиска строки в текстовом файле:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        String tmp;
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           tmp = stream.filter(lines -> lines.contains(item))
                       .foreach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Ответ 5

Я делаю что-то подобное, но на С++. То, что вам нужно сделать, это прочитать строки по одному и разобрать их (перебирайте слова один за другим). У меня есть петля ауттера, которая просматривает все строки и внутри, это еще один цикл, который охватывает все слова. Как только вам понадобится слово, просто выйдите из цикла и верните счетчик или что хотите.

Это мой код. Он в основном разбирает все слова и добавляет их в "индекс". Строка, в которой было введено слово, затем добавляется к вектору и используется для ссылки на строку (содержащую имя файла, всю строку и номер строки) из проиндексированных слов.

ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
    //Add the path to the list of file paths
    textFilePaths.push_back(path);
    int lineNumber = 1;
    while(!txtFile.eof())
    {
        txtFile.getline(line, 200);
        Line * ln = new Line(line, path, lineNumber);
        lineNumber++;
        myList.push_back(ln);
        vector<string> words = lineParser(ln);
        for(unsigned int i = 0; i < words.size(); i++)
        {
            index->addWord(words[i], ln);
        }
    }
    result = true;
}

Ответ 6

Вот код TextScanner

public class TextScanner {

        private static void readFile(String fileName) {
            try {
              File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
              Scanner scanner = new Scanner(file);
              while (scanner.hasNext()) {
                System.out.println(scanner.next());
              }
              scanner.close();
            } catch (FileNotFoundException e) {
              e.printStackTrace();
            }
          }

          public static void main(String[] args) {
            if (args.length != 1) {
              System.err.println("usage: java TextScanner1"
                + "file location");
              System.exit(0);
            }
            readFile(args[0]);
      }
}

Он будет печатать текст с метриками