简体   繁体   中英

InputstreamReader only reading one line?

I have the following written in the onCreate() method of my main activity.

file = new File(this.getFilesDir(), SIMPLE_WORKOUTS);
    writeToFile("Test1, 20, 10, 5, 2, 1", this);
    writeToFile("Test2, 10, 5, 2, 1, 1", this);
    writeToFile("Test3, 1, 1, 2, 3, 5", this);
    String readFrom = readFromFile(this);
    Log.e("TAG", readFrom);

However, the string readFrom is only ever equal to "Test3, 1, 1, 2, 3, 5". I want to be able to store multiple lines of code in a file, and read through the file line by line. The methods writeToFile and readFromFile are as follows:

public void writeToFile(String data, Context context) {
    String existing = readFromFile(context);
    try (OutputStreamWriter fos = new OutputStreamWriter(context.openFileOutput(SIMPLE_WORKOUTS, Context.MODE_PRIVATE))) {

        fos.write(data + "\n");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(SIMPLE_WORKOUTS);

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

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

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

    return ret;
}

Why the inputstreamreader is only reading the last line written to the file? Alternatively, would a Scanner be more suitable for my goal?

You need to write to file in append mode; otherwise, every time you will write to the file, its old content will be overwritten. I believe you can get the file-path from context object. Then, you can do as follows:

//Set true for append mode
BufferedWriter writer = new BufferedWriter(new FileWriter(your-file-path, true));  
writer.write(data);
writer.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM