javafileinputstream

Why do we need FileInputStream in = null; line before try block?


This code from oracle i/o tutorial:

public class CopyBytes {
public static void main(String[] args) throws IOException {

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream("xanadu.txt");
        out = new FileOutputStream("outagain.txt");
        int c;

Why these lines

FileInputStream in = null;
FileOutputStream out = null;

not included to try block in this way (without = null)?

 FileInputStream in = new FileInputStream("xanadu.txt");
 FileOutputStream out = new FileOutputStream("outagain.txt");

Solution

  • You need to declare in and out outside try {...} because you need to close these resources in the finally {...} block.

    FileInputStream in = null;
    FileOutputStream out = null;
    
    try {
      in = new FileInputStream("xanadu.txt");
      out = new FileOutputStream("outagain.txt");
      int c;
      ....
    } catch(Exception e) {
    
    } finally {
       try {
         if(in != null) {       
           in.close();
         }
         if(out != null) {
           out.close();
         }
       catch(Exception e) {...}
    }
    

    If you declare them inside the scope of try {...} the compiler will complain that they could not be resolved.

    If you do:

    try {
      FileInputStream in = new FileInputStream("xanadu.txt");
      FileOutputStream out = new FileOutputStream("outagain.txt");
      int c;
      ....
    } catch(Exception e) {
    
    } finally {
       try {
         if(in != null) { //in could not be resolved error by compiler       
           in.close();
         }
         if(out != null) { //out could not be resolved...
           out.close();
         }
       catch(Exception e) {...}
    }