我想在现有文件中附加文本,但我无法读取它(我可以读取第一个插入的数据)我不知道是什么错误。 这是写入代码(保存在文件中):
FileOutputStream fos = openFileOutput("test",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(text);
oos.flush();
oos.close();
这是如何读取(从文件中读取数据):
FileInputStream fis = openFileInput("test");
ObjectInputStream ois = new ObjectInputStream(fis);
String s=(String) ois.readObject();
while(s != null){
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_SHORT).show();
s=(String) ois.readObject();
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_SHORT).show();
}
请帮助我!代码书写或阅读是否有错误
最佳答案
public boolean writeToFile(String filename,String data){
try {
FileOutputStream fos = openFileOutput(filename,0);
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(filename,0));
out.write(data);
out.close();
return true;
} catch (java.io.IOException e) {
e.printStackTrace();
System.out.println("-----problem in writeToFile()--------");
return false;
}
}
public String readFromFile(String xxx){
StringBuffer returnString = new StringBuffer(""); ;
try{
FileInputStream fstream = openFileInput(xxx);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
returnString.append(strLine);
}
in.close();
}catch (Exception e){//Catch exception if any
e.printStackTrace();
System.out.println("-----problem in readFromFile()--------");
}
return returnString.toString();
}
关于java - 将数据附加到android中的现有文件中并读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5818406/