简体   繁体   English

InputstreamReader 只读取一行?

[英]InputstreamReader only reading one line?

I have the following written in the onCreate() method of my main activity.我在主要活动的onCreate()方法中编写了以下内容。

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".但是,字符串readFrom只等于“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: writeToFilereadFromFile方法如下:

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?为什么inputstreamreader只读取写入文件的最后一行? Alternatively, would a Scanner be more suitable for my goal?或者, Scanner是否更适合我的目标?

You need to write to file in append mode;您需要在append模式下写入文件; 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.我相信您可以从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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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