2016-03-05 84 views
1

我已经得到了文件,它的大小可以根据行而不同。我所知道的唯一的事情是它由相同的模块组成,可以说是7行。所以这意味着.txt可以是7,14,21,70,77等行。我只需要获取每个模块的标题 - 第0行,第7行等。在android中读取特定行fromt .txt文件

我已经写了这个代码工作:

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

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

+0

http://stackoverflow.com/questions/2312756/how-to-read-a-specific-line-using-the-specific-line-number-from-a-file-in-java – sasikumar

+0

我已经读过这个问题,那是我得到这个总体想法的地方。 http://stackoverflow.com/a/2312789/4491661 - 特别是 –

+0

你得到一个缓冲读取器的文件就像这个'BufferedReader br = new BufferedReader(new FileReader(file))',然后'line = br.readLine )' – Bhargav

回答

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

@UmaKanth oops,感谢编辑哈哈! – Bhargav

+0

这个人可以完成工作。尽管它表示“试用资源需要API级别19”。我想它会与早期的设备发生冲突。有没有办法解决这个问题? –

+0

是的,我不知道你的minSdkVersion,所以我选择了代码量最少的方式,虐待它与更老的java vesion的处理资源的风格 – Bhargav