找到解决方案: 您必须像这样打开 Streams:
FileInputStream inputStream = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(inputStream);
与输出相同。如果有人在寻找答案时偶然发现这个问题,这对我来说是固定的。
原始问题:
通过对Toast
s 的一些测试,我发现当我调用构造函数时,ObjectOutputStream
我会IOException
被抛出。
我的代码看起来像这样。请注意,这只是一个测试项目,我什至无法让这个项目工作。
Button b = new Button(this);
b.setText("write");
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
File f = new File("Filepath");
if (!f.exists()) {
f.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f)); //IOException here!
Series x = new Series("Test", 20, 12);
// oos.writeObject(x);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
tv = new TextView(this);
tv.setText("Not read anything yet!");
Button r = new Button(this);
r.setText("Read");
r.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(new File("Filepath")));
Series y = (Series) ois.readObject();
tv.setText(y.getName() + "-" + y.getNumOfSeason() + "-"
+ y.getNumOfEpisode());
ois.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
问题似乎是我的构造函数调用。在我添加部分之前
if (!f.exists()) {
f.createNewFile();
}
我有一个FileNotFoundException
.
我究竟做错了什么?