在Android中从带换行符的文本文件中读取数据时丢失
我有三个字符串,用这段代码写入list.txt文件在Android中从带换行符的文本文件中读取数据时丢失,android,android-file,Android,Android File,我有三个字符串,用这段代码写入list.txt文件 String filepath = Environment.getExternalStorageDirectory().getPath(); String filename=filepath+"/" + FOLDER + "/" + "list.txt" ; FileOutputStream fop = null; File file = null; try { file =new File(filename);
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)));
}
ArrayList数据;
试一试{
字符串filepath=Environment.getExternalStorageDirectory().getPath();
字符串文件名=文件路径+“/”+文件夹+“/”+“list.txt”;
BufferedReader in=新的BufferedReader(新文件读取器(文件名));
字符串音频名称;
audio_name=in.readLine();
数据=新的ArrayList();
而((audio_name=in.readLine())!=null){
添加数据(音频名称);
}
in.close();
}捕获(IOE异常){
System.out.println(“文件读取错误”);
}
例如(int i=0;i音频名=in.readLine()
的第一个实例将读取第一行abc.mp3
,但未使用输入。因此,当循环并存储在数据中时,读取的第一行将是cde.mp3
。您应该删除音频名=in.readLine()的第一个实例
audio_name=in.readLine();
数据=新的ArrayList();
您将第一行读取到audio_name变量中,但从未将其添加到列表中,因此它“丢失”了。如果(!file.exists()){file.createNewFile();
。删除该行。OutputStream将创建文件。冗余?它将使用第一个文件名。是的,这就是丢失行的原因。
audio_name = in.readLine();
data = new ArrayList<String>();