【发布时间】:2018-02-16 12:35:20
【问题描述】:
将 Java 对象保存到文件时遇到问题。我正在使用 Android Studio 编写应用程序。
Outgoing 是我要保存的对象,它包含两个Strings,和一个int。
private FileOutputStream fileOutputStream;
private ObjectOutputStream objectOutputStream;
public void save(String name, String category, int price){
// Open file
try {
fileOutputStream = new FileOutputStream("outgoings.tmp");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
// Saving
Outgoing record;
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
try{
if(name != null){
record = new Outgoing(name, category, price);
objectOutputStream.writeObject(record);
}
}
catch(IOException ioException){
System.err.println(ioException.getMessage());
}
}
// Close file
try{
objectOutputStream.close();
}
catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
}
当我启动应用程序时,执行方法save(),应用程序崩溃。
// Open file
try {
fileOutputStream = new FileOutputStream("outgoings.tmp");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
--> IOException 被抛出,Logcat 显示:
什么是合适的文件路径和我应该使用哪种数据类型?
感谢您的帮助
【问题讨论】:
-
它无法打开文件....?确保当前工作目录是可写的。
-
您的问题的明显答案是由于某些问题无法打开文件。
-
我怀疑这与您正在序列化一个包含另一个类的对象的类有关。
-
我认为您不能在 Android 上创建相对文件,请尝试使用文件的完整路径
-
你有什么问题?
标签: java android android-studio object saving-data