我在主要 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);
但是,字符串 readFrom
永远只等于“Test3, 1, 1, 2, 3, 5”。我希望能够将多行代码存储在一个文件中,并逐行读取文件。 writeToFile
和readFromFile
方法如下:
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;
}
为什么 inputstreamreader
只读取写入文件的最后一行?或者,Scanner
是否更适合我的目标?
最佳答案
需要以append
方式写入文件;否则,每次写入文件时,其旧内容都会被覆盖。我相信您可以从 context
对象中获取文件路径。然后,您可以执行以下操作:
//Set true for append mode
BufferedWriter writer = new BufferedWriter(new FileWriter(your-file-path, true));
writer.write(data);
writer.close();
关于java - InputstreamReader 只读取一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615707/