【问题标题】:Reading an object from a file, than add to an arraylist从文件中读取对象,而不是添加到数组列表
【发布时间】:2015-03-14 13:58:35
【问题描述】:

现在我正在为 java 二进制 I/O 做一个学校作业。

我必须写一些餐厅的菜,把它们写到一个文件中。我也必须从文件中读取这些对象。

现在我可以使用这段代码将菜肴写入文件

private ArrayList<Gerecht> gerechten;

public void writeToFile() throws FileNotFoundException, IOException {

    try {

        DataOutputStream out = new DataOutputStream(new FileOutputStream("Menu.txt"));
        out.writeBytes(gerechten.toString());
    } // catch any file creation errors
    catch (FileNotFoundException e) {
        System.out.println("Error opening file: Menu.txt");

    } catch (IOException e) {
        System.out.println("Error writing file: Menu.txt");

    }
}

一个“Gerecht”对象包含:

一个名字 = naam。

价格 = 价格。

卡路里 = 卡路里。

public abstract class Gerecht extends Menu{
private String naam;
private double prijs;
private int calorien;


public Gerecht(String naam, double prijs, int calorien) {
    this.naam = naam;
    this.prijs = prijs;
    this.calorien=calorien;


}

当我使用上面的构造函数创建一个对象时,我得到了这种输出。

截图:http://gyazo.com/37d8238aa8b35cb0da06e0d4fca10fa0

忽略 Arraylist 中所有 Dishes 的第 4 行,这与超类/子类有关。

现在我必须阅读这个输出,并创建它们的对象。例如:我会在文件中手动输入另一道菜,布局相同,应该有 4 个对象而不是 3 个。

我知道这篇文章很长,但我已经卡了几天了!

【问题讨论】:

标签: java arraylist io binary


【解决方案1】:

你要么需要:

  1. 解析写入的字符串并手动创建对象
  2. 利用对象序列化

    try {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Menu.txt"));
        out.writeObject(gerechten);
    } // catch any file creation errors
    catch (FileNotFoundException e) {
        System.out.println("Error opening file: Menu.txt");
    } catch (IOException e) {
        System.out.println("Error writing file: Menu.txt");
    }
    

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 2018-05-16
    • 2017-03-26
    • 1970-01-01
    • 2017-07-14
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多