2015-09-27 43 views
0

閱讀時,我有三個字符串,其寫入到文件LIST.TXT與此代碼數據丟失,從文本文件換行符的Android

String filepath = Environment.getExternalStorageDirectory().getPath(); 
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ; 
FileOutputStream fop = null; 
File file = null; 

try { 
    file =new File(filename); 
    fop=new FileOutputStream(file,true); 
    // if file doesn't exists, then create it 
    if (!file.exists()) { 
     file.createNewFile(); 
    } 
    filecontent=filecontent+ System.getProperty ("line.separator"); 
    // get the content in bytes 
    byte[] contentInBytes = filecontent.getBytes(); 

    fop.write(contentInBytes); 
    fop.flush(); 
    fop.close(); 

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

文件輸出細節

abc.mp3 
cde.mp3 
edf.mp3 

現在,我想閱讀list.txt中的詳細信息。我用下面的代碼,但輸出只有

cde.mp3 
edf.mp3 

我的代碼發生了什麼?我不知道爲什麼數據abc.mp3消失。

ArrayList<String> data; 
try { 
     String filepath = Environment.getExternalStorageDirectory().getPath(); 
     String filename=filepath+"/" + FOLDER + "/" + "list.txt" ; 
     BufferedReader in = new BufferedReader(new FileReader(filename)); 
     String audio_name; 
     audio_name = in.readLine(); 
     data = new ArrayList<String>(); 
     while ((audio_name = in.readLine()) != null) {     
      data.add(audio_name); 
     } 
     in.close(); 
} catch (IOException e) { 
      System.out.println("File Read Error"); 
} 
for (int i=0;i<data.size();i++) 
    { 
     Log.d("D",String.valueOf(data.get(i))); 
    } 
+0

'if(!file.exists()){ file.createNewFile();'。去掉那個。 OutputStream將創建該文件。 – greenapps

回答

1

audio_name = in.readLine()第一個實例將讀取的第一線abc.mp3但不使用的輸入。因此,您的while循環讀取並存儲在data中的第一行將爲cde.mp3。您應該刪除audio_name = in.readLine()的第一個實例。

+0

冗餘?它消耗第一個文件名。 – greenapps

+0

是的,這是缺失的原因。 – headuck

1
audio_name = in.readLine(); 
data = new ArrayList<String>(); 

您將第一行讀入到您的audio_name變量中,但絕不會將其添加到列表中,這就是爲什麼它「缺失」。