【发布时间】:2010-12-01 21:45:56
【问题描述】:
以下代码有效,但打开一个小文件所需的时间太长(超过一分钟)。 LogCat 显示了很多“GC_FOR_MALLOC freed #### objects / ###### bytes in ##ms”的实例。有什么建议吗?
File dirPath = new File(Environment.getExternalStorageDirectory(), "MyFolder");
String content = getFile("test.txt");
public String getFile(String file){
String content = "";
try {
File dirPathFile = new File(dirPath, file);
FileInputStream fis = new FileInputStream(dirPathFile);
int c;
while((c = fis.read()) != -1) {
content += (char)c;
}
fis.close();
} catch (Exception e) {
getLog("Error (" + e.toString() + ") with: " + file);
}
return content;
}
更新:
这就是现在的样子:
File dirPath = new File(Environment.getExternalStorageDirectory(), "MyFolder");
String content = getFile("test.txt");
public String getFile(String file){
String content = "";
File dirPathFile = new File(dirPath, file);
try {
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(dirPathFile));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
content = new String(text);
} catch (Exception e) {
getLog("Error (" + e.toString() + ") with: " + file);
}
return content;
}
谢谢大家!!
【问题讨论】:
-
我尝试了一些不同的方法,现在速度快了很多。我可以在大约 5 秒内读取一个 200kb 的文件,所以这是一个改进,但是我需要打开大约 5 个这些文件,每个 5 秒仍然很长,所以我将使用 SQL lite 并查询数据反而。我已经编程了很长时间,但是我是android和Java的新手,所以这更像是一个学习练习。非常感谢所有的建议!
标签: android sd-card fileinputstream