我正在尝试将学生 ID 写入 sdcard 的文本文件中。我已经students.txt
在我的 sdcard 中创建了一个名为的文件。
问题是当我写一个值并读取文件时,我只得到文件中的最后一个值。当我打开我的文件时,我只能看到其中写入的最后一个值。
我究竟做错了什么?我正在使用追加模式写入文件,outputStreamWriter
但问题仍然存在。
//function to insert
private void myInsertFunc(String data) {
try {
File file = new File("/sdcard/" + FILENAME);
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append(data);
outputStreamWriter.close();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Student ID: " + data + " Inserted Successfully!", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
//function to read
private void myReadFunc() {
try {
//InputStream inputStream = openFileInput(FILENAME);
//InputStream inputStream = getResources().openRawResource(R.raw.student);
File file = new File("/sdcard/" + FILENAME);
FileInputStream fileInputStream = new FileInputStream(file);
if (fileInputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
//if(receiveString.contains(data))
//{
Toast.makeText(getApplicationContext(), "Student ID: " + receiveString , Toast.LENGTH_SHORT).show();
//break;
//}
}
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}