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

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

请帮助我!代码书写或阅读是否有错误

最佳答案

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/

相关文章:

Java InputStream.read(byte[], int, int) 方法,如何阻塞直到读取了确切的字节数

android - 更新有序的 BroadcastReceiver android 之间的 Intent extras

enums - 在 Java API 中使用枚举

java - 如何从 `Instances` 在 Weka 中创建 `List<Instance>`?

java - SimpleDateFormat 返回带有无效日期字符串的奇怪日期

android - 如何从维基百科文章中提取数据?

android - 针对不安全的 TrustManager 的 Google Play 安全警报

java - HttpPost 中的 org.apache.http.client.ClientProtocolException

android - 在 Android 的 GSON 中反序列化泛型类

java - 使用安卓相机识别颜色