JNorr44
JNorr44

Reputation: 274

Reading bytes from a class

I am trying to get a class from a path on a file system, and get the bytes from it. I have tried what is below, but have had no success. This should just print out the name for now. If anyone has any ideas on how to do what I am doing, please let me know. It may even be easier than this...

public class Driver {
public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the path of the class:  ");
    String from = br.readLine();
    System.out.print("Enter the path to save the .txt file (with bytes):  ");
    String to = br.readLine();
    Class clazz = getClassFromPath(from);
    System.out.println("Loaded <" + clazz.getName() + "> successfully!");
}

public static Class<?> getClassFromPath(String path) {
    try {
        File file = new File(path);
        URL[] urls = {new URL(path)};
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        if (!file.isDirectory() && file.getName().endsWith(".class")) {
            String className = file.getName().substring(0, file.getName().length() - 6);
            className = className.replace('/', '.');
            Class c = cl.loadClass(className);
            return c;
        }
        for (File f : file.listFiles()) {
            if (f.isDirectory() || !f.getName().endsWith(".class")) {
                continue;
            }
            String className = f.getName().substring(0, f.getName().length() - 6);
            className = className.replace('/', '.');
            Class c = cl.loadClass(className);
            return c;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
}

Upvotes: 0

Views: 72

Answers (1)

Jose-Rdz
Jose-Rdz

Reputation: 539

I'm pretty sure you can try something like this:

InputStream stream = clazz.getClassLoader().getResourceAsStream(classAsPath);

where classAsPath is what you're actually doing on your method getClassFromPath

Then you might want to use Apache Commons-io to read the InputStream into a byte[] using something like IOUtils.toByteArray()

Upvotes: 3

Related Questions