2011-04-28 5 views
1

기존 파일에 텍스트를 추가하고 싶지만 읽을 수 없습니다 (처음 삽입 된 데이터를 읽을 수 있음). 나는 실수를 모른다. 이 쓰기 코드 (파일에 저장)입니다 :안드로이드에있는 기존 파일에 데이터를 추가하고 읽으십시오.

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

행복이 나를 도와! 서면이나 독서 코드에 잘못이 있습니까?

답변

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(); 
} 
관련 문제