gpt4 book ai didi

java - 可序列化的简单对象 IOException

转载 作者:行者123 更新时间:2023-12-02 07:09:12 25 4
gpt4 key购买 nike

找到解决方案:你必须像这样打开流:

FileInputStream  inputStream = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(inputStream);

与输出相同。这为我解决了这个问题,如果有人在寻找答案时偶然发现这个问题。

原始问题:通过对 Toast 的一些测试,我发现当我调用 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

我做错了什么?

最佳答案

以下是 FileOutputStream 的 Oracle 文档摘录

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

就您的情况而言,我认为该文件被视为目录,因为它没有扩展名,因此抛出异常。

关于java - 可序列化的简单对象 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com