Read/write file to internal private storage

◇◆丶佛笑我妖孽 提交于 2019-11-28 20:51:18

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

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

//to write

String data = "Hello World";
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME,     
Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();

//to read

String ret = "";

    try {
        InputStream inputStream = openFileInput(FILENAME);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Can not read file: " + e.toString());
    }

    return ret;
}

context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!