【问题标题】:Method to find string inside of the text file. Then getting the following lines up to a certain limit在文本文件中查找字符串的方法。然后让以下几行达到一定的限制
【发布时间】:2011-08-01 19:22:40
【问题描述】:

这就是我目前所拥有的:

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
}

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

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

【问题讨论】:

  • 如果这是家庭作业,应该这样标记。
  • 您可以添加输入文件的示例吗?

标签: java file methods project


【解决方案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
}

【讨论】:

  • 这不会给我包含字符串 studentNumber 的行。
  • 这很有帮助。没想到大家的反应这么快。
  • 通常在 StackOverflow 上,我们通过投票或接受他们的回答来感谢人们。
  • @Joel 每个答案的左边是一个由上/下字符包围的数字。这些向上/向下字符代表对答案的“投票”和反对。一个有很多选票的答案会“排在首位”,这样以后更容易找到。如果你问这个问题,数字附近还应该有一个“勾号”字符的轮廓。单击一次以指示“正确”答案。
  • 您不应该关闭扫描仪吗?
【解决方案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)

【讨论】:

  • 我猜这会读取内存中的完整文件,而@Amir的解决方案不会这样做?
【解决方案3】:

这是在文本文件中查找字符串的 java 8 方法:

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

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

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

【讨论】:

  • 我收到此错误The method foreach(System.out::println) is undefined for the type Stream&lt;String&gt;
  • @Nasser 你把你的jdk设置为1.8了吗?我认为这是 java 版本的问题,因为此功能适用于 java 1.8 及更高版本。
  • 这需要在同一行上找到模式。取决于很多因素,情况可能并非如此。
【解决方案4】:

在阅读文件时,有没有考虑过逐行阅读?这将允许您检查您的行是否包含您正在阅读的文件,然后您可以根据它执行您需要的任何逻辑?

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++;
}

【讨论】:

  • 让我试试。我会回复你的。
【解决方案5】:

这将在 Student.txt 中找到“Mark Sagal”。假设 Student.txt 包含

学生.txt

Amir Amiri
Mark Sagal
Juan Delacruz

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        final String file = "Student.txt";
        String line = null;
        ArrayList<String> fileContents = new ArrayList<>();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader fileBuff = new BufferedReader(fReader);
            while ((line = fileBuff.readLine()) != null) {
                fileContents.add(line);
            }
            fileBuff.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(fileContents.contains("Mark Sagal"));
    }
}

【讨论】:

    【解决方案6】:

    我正在做类似的事情,但在 C++ 中。您需要做的是一次读一行并解析它们(一个接一个地检查单词)。我有一个遍历所有行的外部循环,内部是遍历所有单词的另一个循环。一旦找到你需要的词,就退出循环并返回一个计数器或任何你想要的。

    这是我的代码。它基本上解析出所有单词并将它们添加到“索引”中。然后将单词所在的行添加到向量中,并用于引用索引单词中的行(包含文件名、整行和行号)。

    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;
    }
    

    【讨论】:

    • 虽然有帮助,但 OP 要求基于 Java 的解决方案。 C++ 文件操作与 Java 中的文件操作有很大不同,因此您的答案在这种情况下并不完全有帮助。
    【解决方案7】:

    这是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]);
          }
    }
    

    它将打印带有分隔符的文本

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 2012-08-10
      相关资源
      最近更新 更多