我尝试将数据从我自己的类保存到File!我的班级是
odmiana
代码如下:
od = new odmiana(e1.getText().toString(),e2.getText().toString(),e3.getText().toString(),e4.getText().toString(),e5.getText().toString(),e6.getText().toString());
String filename = "myfile";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(od);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
你能帮助我吗?
答案 0 :(得分:0)
要将类对象写入文件,您的类首先需要实现Serializable
接口。然后你可以将该类的实例写入文件
public static void writeObjectToFile(odmiana obj) {
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream("filename.txt"));
os.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) { e.printStackTrace(); }
}
}