0

我正在编写一个需要一些数据持久性的 Bukkit 插件。这是我为将项目的 ArrayList 保存到文件中所做的代码。

private ArrayList<Project> projects = new ArrayList<Project>;
private String filename = "plugins\\ProjectManager\\projects.cfg";


try {
    FileOutputStream fos = new FileOutputStream(new File(filename));
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(projects);
    oos.close();
} catch (Exception e) {
    getLogger().severe("Unable to save projects to file. Data may have been lost.");
}

在哪里

public class Project implements Serializable {...}

它将创建文件,但不会保存任何内容。关于出了什么问题的任何想法?


好的,我非正式地关闭它。由于其他依赖项与不可序列化的类有关,因此无法以这种方式保存它。感谢您的所有帮助。

4

1 回答 1

0

问题在于您没有向我们展示的代码或错误。这个例子有效

class Main {
    public static void main(String[] ignored) throws IOException, ClassNotFoundException {
        String filename = "config.data";

        List<Project> projects = new ArrayList<Project>();
        projects.add(new Project());
        projects.add(new Project());
        projects.add(new Project());

        FileOutputStream fos = new FileOutputStream(new File(filename));
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(projects);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
        List<Project> projects2 = (List<Project>) ois.readObject();
        ois.close();
        System.out.println("There was " + projects2.size() + " projects saved");
    }

    static class Project implements Serializable {

    }
}

印刷

There was 3 projects saved
于 2013-11-04T23:06:29.703 回答