Search code examples
androidsd-cardfileinputstream

Opening a 12kb text file takes WAY too long....?


The following code works, but takes way too long (over a minute) to open a small file. The LogCat shows a lot of instances of "GC_FOR_MALLOC freed #### objects / ###### bytes in ##ms". Any suggestions?

 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;
 }

Update:

This is what it looks like now:

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;
}

Thank you all!!


Solution

  • Using += on a String is extremely inefficient - it will constantly allocate and deallocate memory, something you need to avoid!

    If you need to constantly add characters, use a StringBuilder and give it a sufficiently big buffer up front.

    However, it's even better to just read the entire file as a byte array and then create a string from that byte array. Use the String(byte[]) constructor.