在Android中从文件读取数据
我必须读取一些储存在手机存储器中文件中的数据。我只能读到,当我在终端上打印结果时,它只打印出一些行。我的文件包含以下数据: 我使用以下代码读取此数据:在Android中从文件读取数据,android,file,Android,File,我必须读取一些储存在手机存储器中文件中的数据。我只能读到,当我在终端上打印结果时,它只打印出一些行。我的文件包含以下数据: 我使用以下代码读取此数据: File sdcard = Environment.getExternalStorageDirectory(); //Get the text file File file = new File(sdcard,"data.txt"); //Read text from
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"data.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
System.out.println(line); //print the result on terminal
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
但在终端中,它不会打印文件的所有行。终端中的结果视图如下所示:
在这种情况下,它只显示最后四个数据,而在其他情况下,它显示所有数据。我不明白为什么。有人能帮我吗?
提前感谢您的帮助。试试这个:
...
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
Log.d("YOUR_TAG", line);
...
从while循环中删除
,并在循环外的Log.d()中写入最终文本
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, "data.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
Log.d("Activity","Final Text----->"+text);
br.close();
} catch (IOException e) {
e.printStackTrace();
//You'll need to add proper error handling here
}
在while循环外打印文本,可能是您的logcat有问题。@RajatMehra它不起作用,只返回四个elements@MirkoMarasco看看我的答案,它会对你有用的:)@米尔科很乐意帮助你如果答案有帮助的话请投票