我想读/写几个字符串到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 :(得分:0)
您可以轻松地让您的班级实施Serializable
并使用ObjectOutputStream
对其进行序列化,并使用ObjectInputStream
对其进行反序列化。