将数据附加到android中的现有文件中并读取它

时间:2011-04-28 12:12:51

标签: java android

我想在现有文件中附加文本,但我无法读取它(我可以读取第一个插入的数据)我不知道错误是什么。 这是写代码(保存在文件中):

     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(); 
      }
请求帮助我!!在写作或阅读代码中有错误

1 个答案:

答案 0 :(得分:0)

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();
}