简体   繁体   English

从类读取字节

[英]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;
}
}

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 您在方法getClassFromPath上实际执行的操作classAsPath

Then you might want to use Apache Commons-io to read the InputStream into a byte[] using something like IOUtils.toByteArray() 然后,您可能想使用Apache Commons-io,使用IOUtils.toByteArray()之类的方法将InputStream读入byte []。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM