从Jar文件中的Class文件读取字节 [英] Read bytes from a Class file within a Jar file

查看:93
本文介绍了从Jar文件中的Class文件读取字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.jar文件,其中有.class个文件和.java个文件.我想将特定的.class文件的内容作为byte[]数组加载.

I have a .jar file which has .class files and .java files. I want to load the contents of a specific .class file as a byte[] array.

static byte[] getBytes(String javaFileName, String jar) throws IOException {
  try (JarFile jarFile = new JarFile(jar)) {
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();

      // We are only interested in .class files spawned by compiling the argument file.
      if (entry.getName().endsWith(".class") &&
          entry.getName().contains(Files.getNameWithoutExtension(javaFileName))) {
        try (InputStream inputStream = jarFile.getInputStream(entry)) {
          return Preconditions.checkNotNull(ByteStreams.toByteArray(inputStream));
        } catch (IOException ioException) {
          System.out.println("Could not obtain class entry for " + entry.getName());
          throw ioException;
        }
      }
    }
  }
}

但是,当我运行此代码时,将向我返回一个空字节数组(new byte[0]).关于我可能在这里做错的任何想法吗?

However, when I run this code, an empty byte array (new byte[0]) is returned to me. Any ideas on what I may be doing wrong here?

该代码可以正常工作!错误是问题的另一部分.无论如何,为了知识起见,把问题放在这里:)

This code works just fine! The error was in another part of the question. Keeping the question here for knowledge's sake anyway :)

推荐答案

这对我有用:

public class Main {
    public static void main(String[] args) {
        try {
            byte[] bytes = getBytes("MeasurePrinter.class", "~/BundleSensorAlarmLib.jar");
            System.out.println(bytesToHex(bytes));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static byte[] getBytes(String javaFileName, String jar) throws IOException {
        // ... inputs check omitted ...
        try (JarFile jarFile = new JarFile(jar)) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();

                // We are only interested in .class files spawned by compiling the argument file.
                if (entry.getName().endsWith(".class") &&
                        entry.getName().contains(javaFileName.substring(0, javaFileName.lastIndexOf(".")))) {
                    try (InputStream inputStream = jarFile.getInputStream(entry)) {
                        return getBytes(inputStream);
                    } catch (IOException ioException) {
                        System.out.println("Could not obtain class entry for " + entry.getName());
                        throw ioException;
                    }
                }
            }
        }
        throw new IOException("File not found");
    }

    private static byte[] getBytes(InputStream is) throws IOException {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();)
        {
            byte[] buffer = new byte[0xFFFF];
            for (int len; (len = is.read(buffer)) != -1;)
                os.write(buffer, 0, len);
            os.flush();
            return os.toByteArray();
        }
    }

    private static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}

从返回的字节数组不为空的意义上说.

in the sense that the returned byte array is not empty.

这篇关于从Jar文件中的Class文件读取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆