我有一个.jar
文件,其中包含.class
文件和.java
文件。我想将特定.class
文件的内容作为byte[]
数组加载。
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]
但是,当我运行此代码时,会向我返回一个空字节数组 ( )。关于我在这里可能做错的任何想法?
编辑:这段代码工作得很好!错误出现在问题的另一部分。无论如何,为了知识而将问题保留在这里:)