Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/write file to internal private storage

I'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:

FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE ); 
fos.write( data.getBytes() ); 
fos.close();

Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:

int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
  fileContent.append((char)ch);
String data = new String(fileContent);

So my question is how to read the file using better way?

like image 898
STeN Avatar asked Mar 06 '11 10:03

STeN


2 Answers

Using FileInputStream.read(byte[]) you can read much more efficiently.

In general you don't want to be reading arbitrary-sized files into memory.

Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.

Here is how you use the byte buffer version of read():

byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
    fileContent.append(new String(buffer));
}
like image 104
Matthew Willis Avatar answered Nov 19 '22 10:11

Matthew Willis


This isn't really Android-specific but more Java oriented.

If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.

InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine()

Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:

String data = new String(ByteStreams.toByteArray(fis));
like image 8
Roshan Avatar answered Nov 19 '22 10:11

Roshan