从android中的.txt文件中读取特定行

时间:2016-03-05 11:35:04

标签: java android android-file

我的文件在行数方面可能会有所不同。我唯一知道的是,它是由相同的模块组成的,比方说,7行。所以这意味着.txt可以是7,14,21,70,77等。我只需要获得每个模块的标题 - 第0行,第7行等等。

我为这份工作编写了这段代码:

    textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );

    List<String> headers = new ArrayList<>();

    if (textFile.exists()) {
        try {
            FileInputStream fs= new FileInputStream(textFile);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
            int lines = 0;
            int headLine = 0;
            while (reader.readLine() != null) { lines++;}
            Log.i("Debug", Integer.toString(lines));
            while(headLine < lines){


                for (int i = 0; i < dateLine - 1; i++)
                {
                    reader.readLine();
                    Log.i("Debug", reader.readLine());
                }
                headers.add(reader.readLine());


                headLine += 7;
            }

            Log.i("Debug", headers.toString());


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

问题是它总是返回[null]。我不知道问题出在哪里,因为我使用溢出的类似问题作为参考。

1 个答案:

答案 0 :(得分:2)

ArrayList<String>  headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
    String line;
    int lineCount = 0;
    while ((line = br.readLine()) != null) {
       // process the line.
       if(lineCount % 7 == 0) {
           heaaderLines.add(line);
       }
       lineCount ++;
    }
} catch (IOException ioEx) {
    ioEx.printStackTrace();
} finally {
    br.close();
}
相关问题