gpt4 book ai didi

java - 可序列化的ArrayList——IOException错误

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

下面的代码返回 IOException。这是我的主要内容:

public class Main 
{

public static void main(String[] args) {

Book b1 = new Book(100, "The Big Book of Top Gear 2010", "Top Gear",
"BBC Books", 120, "Book about cars.");

Book b2 = new Book(200, "The Da Vinci Code", "Dan Brown", "Vatican", 450,
"A fast paced thriller with riddles.");

Book b3 = new Book(300, "Le Petit Nicolas", "Sempe Goscinny", "Folio", 156,
"The adventures of petit Nicolas.");

ArrayList<Book> biblia = new ArrayList<Book>();

biblia.add(b1);

biblia.add(b2);

biblia.add(b3);

File f = new File("objects");

try {

FileInputStream fis = new FileInputStream("objects");

int u = fis.read();

if (u != -1) {

ObjectInputStream ois = new ObjectInputStream(fis);

Bookstore b = (Bookstore) ois.readObject();

ois.close();

} else {

Bookstore b = new Bookstore(biblia);

FileOutputStream fos = new FileOutputStream("objects");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(b);

oos.close();

}

} catch (FileNotFoundException ex1) {

System.out.println("File not found.");

} catch (IOException ex2) {

System.out.println("IO Error.");

} catch (ClassNotFoundException ex3) {

System.out.println("Class not found.");

}

}

这是 Bookstore 类,我只是用它来存储 Book 对象的 ArrayList,以便在对象流中使用它。

public class Bookstore implements Serializable {


private ArrayList<Book> myBooks = new ArrayList<Book>();

public Bookstore(ArrayList<Book> biblia) {

myBooks = biblia;

}

}

我也导入了所有正确的库。我尝试做的是:如果文件不为空,则从那里读取 ArrayList (包含 arraylist 的书店对象)。如果为空就写一个新的。问题是我得到的唯一返回是“IO Error”。我不明白为什么。

最佳答案

测试文件是否存在的方法是错误的。您正在尝试从不存在的文件创建流,并抛出 FileNotFoundException。而不是:

FileInputStream fis = new FileInputStream("objects");            
int u = fis.read();
if (u != -1) {

直接使用

if(f.exists()) { ... }

关于java - 可序列化的ArrayList——IOException错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4742580/

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