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

The following code works, but takes too long (more than a minute) to open a small file. LogCat shows many 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:

It looks like this:

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

Thanks everyone!

+3
source share
6 answers

Using +=in a string is extremely inefficient - it will constantly allocate and free memory, which you need to avoid!

If you need to constantly add characters, use StringBuilderand give it a large enough buffer up.

, . String(byte[]).

+6

content + = (char) c;

, . , . , .

read(byte[] buffer) . .

+2

, , , read (byte []).

, , , String s = s + "a"; , String. StringBuilder, .

+2

, !

+2

:

  • String content += (char)c; - StringBuilder , toString() StringBuilder.
  • You do not use byte [] (or char [], it depends on the implementation) of the buffer for reading from a file. Typically, a 1 Kbyte buffer is optimal, instead of reading one byte at a time.
0
source

Source: https://habr.com/ru/post/1778000/


All Articles