如何找到该行的索引?

时间:2014-04-04 14:53:16

标签: android

我正在使用以下代码从文件中读取数据,但我无法找到该行的索引?

public static ArrayList<String> searchInFile(String word) {


    ArrayList<String> result = new ArrayList<String>();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(new File("input.txt"));
    } catch (FileNotFoundException e1) {
        System.err.println("File input.txt not found!");
        e1.printStackTrace();
    }

    BufferedReader br = new BufferedReader(file);
    String line;
    try {
        while ((line = br.readLine()) != null) {
           if (line.contains(word)) {
              result.Add(line);
           }
        }

    } catch (IOException e) {
        System.err.println("Error when processing the file!");
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                System.err.println("Unexpected error");
                e.printStackTrace();
            }
        }

    }
    return result;
}

那么如何才能找到该行的索引?

1 个答案:

答案 0 :(得分:2)

您需要创建一个计数器整数变量,以便为您跟踪行索引。

   int ctr =0;
    while ((line = br.readLine()) != null) {
       if (line.contains(word)) {
          result.Add(line);
       }
       ctr++;
    }

希望它有所帮助!