Search code examples
javaandroidandroid-file

Reading specific line fromt .txt file in android


I've got the file, which can vary in size, in terms of lines. The only thing I know is that it's made of same modules of, lets say, 7 lines. So it means that .txt can be 7, 14, 21, 70, 77 etc. lines. I need to get only header of each module - line 0, 7 and so on.

I've written this code for the job:

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

The problem is that it always returns [null]. I do not know where's the problem, since I used similar questions from overflow as references.


Solution

  • 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();
    }