2013-03-02 59 views
0

我想讀/寫幾個字符串轉換成Android文件Android的讀/寫幾個字符串

所以我寫的樹EditTexts信息

public void save(Person p) { 

    try { 
     FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
     fos.write(p.getName().getBytes()); 
     fos.write(p.getSurname().getBytes()); 
     fos.write(p.getAge().getBytes()); 
     fos.close(); 
     Toast toast = Toast.makeText(getApplicationContext(), 
        "Info was saved!", Toast.LENGTH_SHORT); 
     toast.show(); 
    } catch (FileNotFoundException e){ 
     e.printStackTrace(); 
     Toast toast = Toast.makeText(getApplicationContext(), 
       "File not found exeption!", Toast.LENGTH_SHORT); 
     toast.show(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Toast toast = Toast.makeText(getApplicationContext(), 
        "Input/Output Exeption!", Toast.LENGTH_SHORT); 
     toast.show(); 
    } 
} 

我嘗試加載回的信息與方法

private void load(){ 
    String value = ""; 
    FileInputStream fis; 

    try { 
     fis = openFileInput(FILENAME); 
     byte[] input = new byte[fis.available()]; 
     while(fis.read(input) != -1) { 
      value += new String(input); 
     } 
     edName.setText(value); 
     while(fis.read(input) != -1) { 
      value += new String(input); 
     } 
     edSurname.setText(value); 
     while(fis.read(input) != -1) { 
      value += new String(input); 
     } 
     edAge.setText(value); 
     fis.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Toast toast = Toast.makeText(getApplicationContext(), 
       "Input/Output Exeption!", Toast.LENGTH_SHORT); 
     toast.show(); 
    } 

} 

它加載信息,但所有數據都組合在一行中。我如何讀取行的一些數據行?

或者我可以寫/讀一些類及其字段?(在我的例子有類人用領域的姓名,年齡,男)

+0

它的工作原理,謝謝 – user2105282 2013-03-09 08:35:03

回答

0

那麼你可以很容易地讓你的類實現Serializable和使用, ObjectOutputStream來序列化它,並且ObjectInputStream來反序列化它。