Java ObjectOutputStream Write load(File file, final ClassLoader... loaders)

Here you can find the source of load(File file, final ClassLoader... loaders)

Description

load

License

Open Source License

Declaration

public static Object load(File file, final ClassLoader... loaders) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import java.io.ObjectStreamClass;

import java.util.zip.GZIPInputStream;

public class Main {
    public static Object load(String filepath) {
        return load(new File(filepath));
    }//from w  ww . ja v a  2s .  com

    public static Object load(File file) {
        return load(file, new ClassLoader[] { Thread.currentThread().getContextClassLoader() });
    }

    public static Object load(File file, final ClassLoader... loaders) {
        try {
            InputStream fis = new FileInputStream(file);
            if (file.getName().endsWith(".gz"))
                fis = new GZIPInputStream(fis);
            ObjectInputStream oIn = new ObjectInputStream(fis) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    String className = desc.getName();
                    try {
                        return Class.forName(className);
                    } catch (ClassNotFoundException exc) {
                        for (ClassLoader cl : loaders) {
                            try {
                                return cl.loadClass(className);
                            } catch (ClassNotFoundException e) {
                            }
                        }
                        throw new ClassNotFoundException(className);
                    }
                }
            };
            Object serialized = oIn.readObject();
            oIn.close();
            return serialized;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. load(File f)
  2. load(File file)
  3. load(File file)
  4. load(File file, Class type)
  5. load(String fileName)
  6. load(String filename)
  7. load(String name, Class resultClass)
  8. load(String path)