Any ideas why I am getting this error? (Yes, I looked up the error, and still haven’t found a solution)
My error:
Exception in thread "main" java.lang.ClassFormatError: Truncated class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at org.fellixombc.mysql.util.MysqlClassLoader.findClass(MysqlClassLoader.java:22)
at org.fellixombc.mysql.util.MysqlClassLoader.loadClass(MysqlClassLoader.java:14)
at org.fellixombc.mysql.Main.main(Main.java:9)
Files:
Main.java
package org.fellixombc.mysql;
import org.fellixombc.mysql.util.MysqlClassLoader;
public class Main {
public static void main(String[] args) {
MysqlClassLoader mcl = new MysqlClassLoader();
try {
mcl.loadClass("org.fellixombc.mysql.net.Client");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Client.java:
package org.fellixombc.mysql.net;
public class Client {
public Client() {
System.out.println("Hello!");
}
}
MysqlClassLoder.java:
package org.fellixombc.mysql.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class MysqlClassLoader extends ClassLoader {
public MysqlClassLoader() {
super(MysqlClassLoader.class.getClassLoader());
}
@Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}
@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
byte[] b = null;
try {
b = loadClassData(className);
Class c = defineClass(className, b, 0, b.length);
if(c != null)
return c;
return super.findClass(className);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] loadClassData(String className) throws IOException {
int size = className.length();
byte buff[] = new byte[size];
// Open the file
FileInputStream fis = new FileInputStream("bin/" + className.replace('.', File.separatorChar) + ".class");
fis.available();
fis.read(buff);
fis.close();
return buff;
}
}
Yes, you’re reading at most a byte count equal to the number of characters in the filename. Instead, you need to read the whole file. Here’s one method, using readFully as you suggested.
Since you’re not handling built-in classes like Object, I think you need to catch the FileNotFoundException from loadClassData in your findClass, then call super.findClass. E.g.: