打开一个12kb的文本文件需要花费太长时间......?

Mr.*_*cky 3 android sd-card fileinputstream

以下代码可以正常工作,但需要花费太长时间(超过一分钟)才能打开一个小文件.LogCat显示了很多"## ms"中"GC_FOR_MALLOC释放#### objects/######字节"的实例.有什么建议?

 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;
 }
Run Code Online (Sandbox Code Playgroud)

更新:

这就是现在的样子:

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你们!!

Ebo*_*ike 6

使用+=上的绳子是非常低效的-它就会不断地分配和释放内存,是你需要避免的!

如果你需要不断添加字符,请使用a StringBuilder并在前面给它一个足够大的缓冲区.

但是,最好只将整个文件作为字节数组读取,然后从该字节数组中创建一个字符串.使用String(byte[])构造函数.