package example8_3_FileOpening; import java.io.*; public class OpeningBinaryFilesExample { public static void main(String[] args) { // Ways to open a binary file. // All of them throw a FileNotFoundException. try { // 1 File f1 = new File("D:\\MyDocs\\Desktop\\Example.txt"); InputStream inputStream1 = new FileInputStream(f1); // 2 File f2 = new File("D:\\MyDocs\\Desktop\\ExampleFoo.txt"); if(f2.isFile()) { FileInputStream fileInputStream2 = new FileInputStream(f2); // NOTE: You still have to surround it with the try-catch block. // Because although we know the file is there, the method still // "throws" a FileNotFoundException. } else { System.err.println("Warning: Could not open file."); System.out.println("Warning: Could not find file."); } // 3 InputStream inputStream3 = new FileInputStream("D:\\MyDocs\\Desktop\\Example.txt"); // 4 FileInputStream fileInputStream4 = new FileInputStream("D:\\MyDocs\\Desktop\\Example.txt"); // 5 // Make your own! This list is far from exhaustive! } catch (FileNotFoundException e) { System.out.println("An error occurred while attempting to open one of the files: "+e.getMessage()); } //File file = new File("D:\\MyDocs\\Desktop\\Example.txt"); // File file = new File("D:\\MyDocs\\Desktop\\Java.txt"); // boolean isDir = file.isDirectory(); System.out.println("Is it a directory? "+isDir); // Should be false -- it's a file, not a directory. boolean isFile = file.isFile(); System.out.println("Is it a \"normal\" file? "+isFile); // Should be false -- it's a file, not a directory. InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { System.err.println("Warning: We could not find the file!"); } if(null != inputStream) { int myByte; int count = 0; try { for(; (myByte = inputStream.read()) != -1; count ++) { String asCharString; if(myByte < 0x20) { asCharString = "Non-printing character"; } else { asCharString = "as char: "+(char)myByte; } System.out.println("Byte index "+count+": "+Integer.toHexString(myByte)+" ("+asCharString+")"); } } catch (IOException e) { System.err.println("Warning: IOException occured while processing the input stream, while attempting " + "to read byte "+count+" Message: "+e.getMessage()); } } } }