从包中读取对象 - java

时间:2014-07-09 14:15:55

标签: java object

如何从包中读取对象? 我把我的对象放到myObject.data文件..

  • 对象名称= myObject.data

  • 包名称为= examplePackage

    MyObject value = null;
    try {
        try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(
                "PACKAGE ....... ? myData.data""
        ))) {
            value = (MyObject) is.readObject();
        }
    } catch (IOException | ClassNotFoundException e) {
        System.out.println("Error: " + e);
    }
    return value;
    

我尝试了getClass().getResource()但无效

谢谢

1 个答案:

答案 0 :(得分:0)

按如下方式更改代码:

MyObject value = null;
try {
    try (ObjectInputStream is = new ObjectInputStream(
      getClass().getClassLoader().getResourceAsStream("data/hm_pj.data"); 
    ))) {
        value = (MyObject) is.readObject();
    }
} catch (IOException | ClassNotFoundException e) {
    System.out.println("Error: " + e);
}
return value;