Reputation: 1085
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?
Upvotes: 0
Views: 2735
Reputation: 2273
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.
Upvotes: 1