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

标签 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]。我不知道哪里出了问题,因为我引用了 overflow 中类似的问题。

最佳答案

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

关于java - 从android中的.txt文件中读取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35813590/

相关文章:

java - JFileChooser,保存多种文件类型

java - Java 中的 HTTP 客户端连接

android - 绘制带圆角的ImageView时的效率

Android 保存文件权限被拒绝

java - 在包级别检查 JAR 使用情况

java - 通过Java实现Apple推送通知服务

java - DVM 是解释器还是编译器?

java - 方法需要对象并从扩展类中查找对象

java - java.io.File 中 mkdir() 和 mkdirs() 的区别

android - Javascript 接口(interface),错误 "Uncaught Error: Error calling method on NPObject"