user1433018
user1433018

Reputation:

Load current class into JarOutputStream

I am building an application that must load the current class at runtime, and add it to a different .jar that I am creating. I have a method that adds files to a jar.

private static void add(File source, JarOutputStream target,
        Manifest manifest) throws IOException {
    BufferedInputStream in = null;
    try {
        String name = source.getName();
        JarEntry entry = new JarEntry(name);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(new FileInputStream(source));

        byte[] buffer = new byte[1024];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            target.write(buffer, 0, count);
        }
        target.closeEntry();
    } finally {
        if (in != null)
            in.close();
    }
}

My problem is this: I can't seem to find out how to add the current class into a file at runtime. I have tried this:

File classFile= new File(getClass().getResource("MyClass.class").getPath());

but I get a null pointer exception. Any help would be greatly appreciated.

Upvotes: 0

Views: 264

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

Don't try to get the class file as a File - just fetch the stream directly:

InputStream classFile = getClass().getResourceAsStream("MyClass.class");

You'll need to modify your add method to take a target name and an input stream, of course. (Potentially overload it, so you've still got the existing method available, which would just open the file, call the other method, then close the stream.)

Upvotes: 1

Related Questions