java的class文件的前4个字节叫做magic number,
用来识别是否为java的class文件.
package pkg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author qefee.com
*
*/
public class MagicNumber {
public static void main(String[] args) {
String pathname = "./bin/pkg/MagicNumber.class";
File file = new File(pathname);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int magicNumber = 0;
magicNumber = fis.read();
magicNumber = (magicNumber << 8) ^ fis.read();
magicNumber = (magicNumber << 8) ^ fis.read();
magicNumber = (magicNumber << 8) ^ fis.read();
String magicNumberString = Integer.toHexString(magicNumber);
System.out.println(magicNumber);
System.out.println(magicNumberString);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
或者
package pkg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author qefee.com
*
*/
public class MagicNumber {
public static void main(String[] args) {
String pathname = "./bin/pkg/MagicNumber.class";
File file = new File(pathname);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.print(Integer.toHexString(fis.read()));
System.out.print(Integer.toHexString(fis.read()));
System.out.print(Integer.toHexString(fis.read()));
System.out.print(Integer.toHexString(fis.read()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
输出
cafebabe