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