2013-03-02 58 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来反序列化它。