Advertisement
joseleonweb

Untitled

Feb 27th, 2021
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. import java.io.*;
  2.  
  3. public class ShowFile2 {
  4.  
  5.     public static void main(String[] args) {
  6.         int i;
  7.         FileInputStream fin = null;  // Here, fin is initialized to null
  8.        
  9.         // First confirm that a file has been specified.
  10.         if(args.length != 1) {
  11.             System.out.println("Usage: ShowFile filename");
  12.             return;
  13.         }
  14.        
  15.         // The following code opens a file, reads characters until EOF
  16.         // is encountered, and then closes the file via a finally block.
  17.         try {
  18.             fin = new FileInputStream(args[0]);
  19.  
  20.             do {
  21.                 i = fin.read();
  22.                 if(i != -1) System.out.print((char) i);
  23.             } while(i != -1);
  24.         } catch(FileNotFoundException exc) {
  25.             System.out.println("File Not Found");
  26.         } catch(IOException exc) {
  27.             System.out.println("An I/O Error Ocurred");
  28.         } finally {
  29.             // Close file in all cases
  30.             try {
  31.                 if(fin != null) fin.close(); // Close the file only if fin is not null
  32.             } catch(IOException exc) {
  33.                 System.out.println("Error Closing File");
  34.             }
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement