0

On my application I need save and load a small xml file. I'd like save and load it on internal storage but I have speed problem for read this file. This file is very small (about 20/30 lines). I have try this code:

        try {
        FileInputStream file = openFileInput("map.xml");
        int c;
        String xml = "";
        while( (c = file.read()) != -1){
            xml = xml + Character.toString((char)c);
        }

        readXMLdata(xml);

        mapRestore = true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

then I have try to save and load the same file to external storage with this code:

        String data = "";

    try {
        File myFile = new File(file_xml);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        String aBuffer = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow + "\n";
        }
        data = aBuffer;
        myReader.close();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    return data;

I have do all test on my Nexus S. If use internal storage I get a lag to read file (some seconds), if I use external storage I don't have it.

Any solution?

Martin
  • 1,065
  • 1
  • 17
  • 36
  • Have you tried the [MAT](http://stackoverflow.com/questions/6080906/memory-analyzer-tool-in-android)? – Skynet Jun 01 '14 at 16:16
  • Even though I cannot believe that being the true problem, String concatenation is very ineffective as Strings are immutables. I would prefer a StringBuffer of some sort, appending each String in the while loop and calling toString() on the StringBuffer object at the end. – cYrixmorten Jun 01 '14 at 16:31

1 Answers1

1

Solution is pretty obvious - just use BufferedReader. In your second sample use you use it, but in the first you don't. That's why you have difference in reading performance.

When you have just FileInputStream and make calls to read method it will actually read data each time from internal storage which is not so fast. When you use BufferedReader or BufferedInputStream data will be read into memory buffer first and then when you call readLine data is read from this buffer. It dramatically decrease the number of IO operations on internal storage and performs a lot faster.

Andrei Mankevich
  • 2,253
  • 16
  • 15