2015-09-27 52 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变量中,但绝不会将其添加到列表中,这就是为什么它“缺失”。