Read/write file to internal private storage

前端 未结 4 1196
太阳男子
太阳男子 2020-12-14 12:14

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

相关标签:
4条回答
  • 2020-12-14 12:34

    //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;
    }
    
    0 讨论(0)
  • 2020-12-14 12:34

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

    0 讨论(0)
  • 2020-12-14 12:35

    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));
    }
    
    0 讨论(0)
  • 2020-12-14 12:52

    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));
    
    0 讨论(0)
提交回复
热议问题