Description:
I wrote a Java program that checks whether the content of the given file begins with the Java class File Format magic number 0xCAFEBABE
, in big-endian byte order.
It prints a success message if:
- The first 4 bytes match the magic number
It prints an error message if:
- The file doesn't exist or cannot be read
- The file contains less than 4 bytes
- The first 4 bytes don't match the magic number
It prints a usage message if:
- A file is not given as input
Code:
import java.io.*;
public class Magic {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java Magic <FILE>");
return;
}
try {
if (isMagicPresent(args[0])) {
System.out.println(String.format("'%s' contains the magic number.", args[0]));
} else {
System.out.println(String.format("'%s' doesn't contain the magic number.", args[0]));
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
private static boolean isMagicPresent(String file) throws IOException {
try (InputStream instream = new FileInputStream(file)) {
byte[] bytes = new byte[4];
int readCount = instream.read(bytes);
if (readCount == 4) {
return Byte.toUnsignedInt(bytes[0]) == 0xCA &&
Byte.toUnsignedInt(bytes[1]) == 0xFE &&
Byte.toUnsignedInt(bytes[2]) == 0xBA &&
Byte.toUnsignedInt(bytes[3]) == 0xBE;
}
}
return false;
}
}
Question:
How can I improve the above code in terms of:
- Readability
- Performance
- Boundary case and error handling