简体   繁体   English

如何读取/写入在文件中具有链接列表的对象

[英]How to read/write an object that has linked lists in a file

I have these classes: "MyClass1", "MyClass2", "MyClass3" and "MyMainClass", 我有以下类别:“ MyClass1”,“ MyClass2”,“ MyClass3”和“ MyMainClass”,

public class MyMainClass implements Serializable {
     private String att1, att2, att3;
     private int att4, att5, att6;
     private LinkedList <MyClass1> myClass1List = new LinkedList<MyClass1>();
     private LinkedList <MyClass2> myClass2List = new LinkedList<MyClass2>();
     private LinkedList <MyClass3> myClass3List = new LinkedList<MyClass3>();
}

My program create registers (Objects) of "MyMainClass" and deposit it in a LinkedList. 我的程序创建“ MyMainClass”的寄存器(对象)并将其存放在LinkedList中。 I want to save the LinkedList of the objects in a file to get them after i reopen my program. 我想在重新打开程序后将对象的LinkedList保存在文件中以获取它们。 What's the way to do it? 怎么做呢? I have tried with ObjectOutputStream, but doesn't work. 我已尝试使用ObjectOutputStream,但无法正常工作。 Thanks. 谢谢。

Edit: My code to add an object(I just read an example and tried): 编辑:我的代码添加一个对象(我只是读一个示例,并尝试):

public static void addObject (MyMainClass p) {
    try {
        outputStream = new ObjectOutputStream(new FileOutputStream("myfile.dat"));
        outputStream.writeObject(p);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}

Note: "MyClass1", "MyClass2", "MyClass3" are Serializable. 注意:“ MyClass1”,“ MyClass2”,“ MyClass3”是可序列化的。

I used following for my highschool project long time ago. 很久以前,我在高中项目中使用了关注对象。 Due to my poor English skills I do not really understand what class you wish to save and load (LinkedList or myMainClass), but I used this solution to successfully store and load any of my custom objects. 由于我的英语水平不佳,我不太了解要保存和加载的类(LinkedList或myMainClass),但是我使用此解决方案成功存储和加载了任何自定义对象。 I hope you find it handy. 希望您会觉得方便。

Usage: 用法:

myMainClass object;
//
// ... your code fillin up the content of object
//
MyIO io = new MyIO();
io.save("", "myfile.dat", object); // "" as first argument will make java use current working directory

// to load the object:

myMainObject object = (myMainObject) io.load("", "myfile.dat"); 

Source: 资源:

import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class MyIO {

    // String path - path to the directory where the file is supposed to be saved.
    // String filename - the name of the file
    // Object data - object that you wish to save in the file. In your case "myMainClass"

    public void save(String path, String filename, Object data) {
        try {
            FileOutputStream fos = new FileOutputStream(path + filename, false);
            GZIPOutputStream gzos = new GZIPOutputStream(fos);
            ObjectOutputStream out = new ObjectOutputStream(gzos);
            out.writeObject(data);
            out.flush();
            out.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    // String path - path to the directory where the file is stored
    // String filename - the name of the file
    // The function returns java object which can be cast to myMainClass.

    public Object load(String path, String filename) {
        try {
            FileInputStream fis = new FileInputStream(path + filename);
            GZIPInputStream gzis = new GZIPInputStream(fis);
            ObjectInputStream in = new ObjectInputStream(gzis);
            Object data = in.readObject();
            in.close();
            return data;
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }
}

I would make "myClass1", "myClass2", and "myClass3" Serializable , then wrap myClass1List , myClass2List , and myClass3List (and any other data you want to save) in another serializable class so you can use serialization/deserialization to save and restore all of the program state at once. 我将使“ myClass1”,“ myClass2”和“ myClass3”成为可序列化的 ,然后将myClass1ListmyClass2ListmyClass3List (以及要保存的任何其他数据)包装在另一个可序列化的类中,以便可以使用序列化/反序列化来保存和还原所有程序状态一次。

Unless myMainClass is that wrapper, in which case you need to declare that they all implement Serializable. 除非myMainClass是该包装器,否则,您需要声明它们都实现了Serializable。

myMainClass isn't marked Serializable . myMainClass没有标记为Serializable Also, are myClass1 , myClass2 , and myClass3 serializable as well? 另外, myClass1myClass2myClass3序列化吗? If not, they should be. 如果没有,他们应该。

On another note, please follow Java naming conventions; 另外,请遵循Java命名约定。 class name should start with an uppercase letter. 类名应以大写字母开头。

UPDATE 更新

Are you sure that it's not writing to the file, or is it that the code is throwing exceptions that you cannot see? 您确定它没有写入文件,还是代码抛出了您看不到的异常?

In all your catch blocks, you have System.exit(1) , which gives you absolutely no information about any exceptions that are happening; 在所有catch块中,都有System.exit(1) ,它绝对不会为您提供有关正在发生的任何异常的信息。 you're essentially swallowing them. 您实际上是在吞食他们。 You should at least print out the stacktrace ( ex.printStackTrace() ) so you can see what is going wrong. 您至少应该打印出ex.printStackTrace()ex.printStackTrace() ),以便查看出了什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM