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;
}
}
}
}
}
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?
EDIT: This code works just fine! The error was in another part of the question. Keeping the question here for knowledge's sake anyway :)