ReadBinaryNIO2.java
Select all
/* ReadBinaryNIO2.java Dave Klick CIS 260 2014-01-29 In-class demonstration of new Java NIO features for reading binary data files. */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class ReadBinaryNIO2 { public static void main(String[] args) { if (args.length == 0) { // No command line arguments were supplied System.out.println("Usage: java ReadBinaryNIO2 filelist"); } else { for (String filename : args) { System.out.println("Specs for: " + filename); Path file = Paths.get(filename); if (!Files.exists(file)) { System.err.println("File does not exist"); continue; // skip rest of loop, process next argument } try { // Files.readAllBytes will handle opening and closing // the file - even if there are errors byte[] buffer = Files.readAllBytes(file); // the & 0xFF eliminates the "sign" of the byte if ((buffer[0x00] & 0xFF) == 0xCA) { // this match indicates a Java class file System.out.println("Match - Java class file"); } else { // this indicates the file was not a Java class file System.out.println("No match - not a Java class file"); } System.out.println(); } catch (IOException e) { System.out.println("Error reading file"); } } } } }