0

我想将一些字符串读/写到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();
    }

}

它加载信息,但所有数据都合并在一行中。我怎样才能逐行读取一些数据行?

或者我可以用它的字段来写/读一些类吗?(在我的例子中,有一个类 Person 有字段 Name、Surname、Age、Male)

4

1 回答 1

0

好吧,您可以轻松地让您的类实现Serializable和使用并ObjectOutputStream对其进行序列化和ObjectInputStream反序列化。

于 2013-03-02T15:43:42.430 回答