2016-03-05 41 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