编写一个读取二进制文件的方法

发布于 2024-10-10 14:44:46 字数 866 浏览 3 评论 0原文

我想编写一个从二进制文件读取对象的方法,但我想使用泛型来概括它。

我有这段代码:

@SuppressWarnings ("unchecked")
public static <T> T readFromBinaryFile (String filename){
T obj = null;

if (FileUtils.existsFile (filename)){
    ObjectInputStream ois = null;
    try{
        ois = new ObjectInputStream (new FileInputStream (filename));
        obj = (T)ois.readObject ();
    }catch (IOException e){
        Debug.out (e);
    }catch (ClassNotFoundException e){
        Debug.out (e);
    }finally{
        try{
            if (ois != null) ois.close();
        }catch (IOException e){
            Debug.out (e);
        }
    }
}

return obj;

}

当我执行它时,我得到一个 ClassCastException。我对java中的模板一无所知,所以任何信息都会受到赞赏。我读过一些与擦除、编译时和执行时相关的内容,但我不太明白为什么会出现这个 ClassCastException。

谢谢。

编辑:我这样调用该方法: FileUtils.readFromBinaryFile(文件名);(不带“”)

I want to write a method that reads an object from a binary file but I want to generalize it using generics.

I have this code:

@SuppressWarnings ("unchecked")
public static <T> T readFromBinaryFile (String filename){
T obj = null;

if (FileUtils.existsFile (filename)){
    ObjectInputStream ois = null;
    try{
        ois = new ObjectInputStream (new FileInputStream (filename));
        obj = (T)ois.readObject ();
    }catch (IOException e){
        Debug.out (e);
    }catch (ClassNotFoundException e){
        Debug.out (e);
    }finally{
        try{
            if (ois != null) ois.close();
        }catch (IOException e){
            Debug.out (e);
        }
    }
}

return obj;

}

When I execute it I get a ClassCastException. I don't know anything about templates in java so any information will be apreciated. I've read something related to erasure, compile-time and execution-time but I don't understand very well why I get this ClassCastException.

Thanks.

EDIT: I call the method like this:
FileUtils.readFromBinaryFile (filename); (Without "")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜访吸血鬼 2024-10-17 14:44:46

Java中有模板吗?只需使用 Object 而不是 T。在 Java 中,一切都从基础上派生自 Object,因此您不需要 T obj,而是 Object obj。

Are there templates in Java? Just use Object instead of T. In Java everything derives from Object at the base, so you don't want T obj but Object obj.

ˉ厌 2024-10-17 14:44:46

ClassCastException 意味着您读取的类型与您期望的类型(并转换为)不匹配。我建议您查看在调试器(或日志消息)中读取的对象,并将其与您期望的类型进行比较。

A ClassCastException means the type you read didn't match the type you were expecting (and cast to) I suggest you see which object you are read in a debugger (or a log message) and compare it with what you are expecting.

萌梦深 2024-10-17 14:44:46

你调用的方法是错误的。
只需这样做:

FileUtils.readFromBinaryFile (filename); 

您所调用的是所谓的泛型方法。

“我们不必将实际类型参数传递给泛型方法。编译器会根据实际参数的类型为我们推断类型参数。它通常会推断出最具体的类型参数,从而使调用类型正确。”

编辑:

我已经尝试过你的例子并且它有效(我实际上评论了一些行)

    private static String filename = "number.serialized";

    public static void main(String[] args) {
        Double d = 3.14;
        writeToBinary(d, filename);
        Double readD = readFromBinaryFile(filename);
        System.out.println(readD);
    }

    @SuppressWarnings ("unchecked")
    public static <T> T readFromBinaryFile(String filename) {
        T obj = null;
        File file = new File(filename);
        if (file.exists()) {
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(filename));
                obj = (T)ois.readObject();
            } catch (IOException e) {
            } catch (ClassNotFoundException e) {
            } finally {
                try {
                    if (ois != null)
                        ois.close();
                } catch (IOException e) {
                }
            }
        }
        return obj;
    }

    public static <T> void writeToBinary(T obj, String filename) 
    {
        try {
            FileOutputStream fis = new FileOutputStream(filename);
            ObjectOutputStream oos = new ObjectOutputStream(fis);
            oos.writeObject(obj);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }

You're calling your method wrong.
Just do it this way:

FileUtils.readFromBinaryFile (filename); 

What you're calling is so-called generic method.

"We don't have to pass an actual type argument to a generic method. The compiler infers the type argument for us, based on the types of the actual arguments. It will generally infer the most specific type argument that will make the call type-correct." source

EDIT:

I've tried your example and it works (I had actually comment some lines)

    private static String filename = "number.serialized";

    public static void main(String[] args) {
        Double d = 3.14;
        writeToBinary(d, filename);
        Double readD = readFromBinaryFile(filename);
        System.out.println(readD);
    }

    @SuppressWarnings ("unchecked")
    public static <T> T readFromBinaryFile(String filename) {
        T obj = null;
        File file = new File(filename);
        if (file.exists()) {
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(filename));
                obj = (T)ois.readObject();
            } catch (IOException e) {
            } catch (ClassNotFoundException e) {
            } finally {
                try {
                    if (ois != null)
                        ois.close();
                } catch (IOException e) {
                }
            }
        }
        return obj;
    }

    public static <T> void writeToBinary(T obj, String filename) 
    {
        try {
            FileOutputStream fis = new FileOutputStream(filename);
            ObjectOutputStream oos = new ObjectOutputStream(fis);
            oos.writeObject(obj);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文