Exception in thread "main" java.lang.ClassFormatError: Incompatible magic
value 813187905 in class file
I understand the error, as it's quite clear. I need to somehow get java's magic value, 0xCAFEBABE
(hex) written to the .java file I'm writing programmatically first. I've read all the answers to similar questions but they all point to bringing in 3rd party libraries to write the java file programmatically.
I can't help but think that there is a relatively straight forward solution to this without bringing in a 3rd party lib? How can I write a hex value to an arbitrary file?
Right now, I'm taking a string. converting it to bytes, and then writing those bytes to a FileInputStream
which then dumps to a file with .java extension. Code I'm using is below. How can I instead of writing bytes, write hex values? Encodings are not my strong suite so this problem is really giving me some trouble.
Code I'm using to write my java file:
public void writeJavaFile() throws IOException
{
String testString = "class test { public test() {} public void printTest()
{ System.out.println(\"yoooo\");}}";
String filename = "test.java";
OutputStream outputStream = new FileOutputStream(filename);
outputStream.write(testString.getBytes());
outputStream.flush();
outputStream.close();
}
I was thinking about this problem all wrong and therefore probably posted a misaligned question. I was under the assumption I was needing to compile my own java file to class file which is where the magic value is actually written.
Obviously I can just have java's compiler compile my programmatically written java file. Here is the code I used to get this to work: