开发者

append data in existing file in android and read it

开发者 https://www.devze.com 2023-03-01 12:38 出处:网络
i want to append a text in an existing file but i can not read it(i can read the first inserted data) i do not know what is the mistake .

i want to append a text in an existing file but i can not read it(i can read the first inserted data) i do not know what is the mistake . this is the write code(save in file):

     FileOutputStream fos = openFileOutput("test",MODE_APPEND);        
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(text);

      oos.flush();

      oos.close(); 

and this is how to read(read the data from the file):

     FileInputStream fis = openFileInput("test");

      ObjectInputStream ois = new ObjectInputStream(fis);
  String s=(String开发者_JAVA百科) 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(); 
      }

pleas help me !! are there a wrong in writing or in the reading code


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

精彩评论

暂无评论...
验证码 换一张
取 消