Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileInputStream Initialization...

 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;

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

int i;
//FileInputStream fin;
FileInputStream fin = new FileInputStream(args[0]);
try {
fin = new FileInputStream(args[0]);
}
catch ( FileNotFoundException e) {
System.out.println( "File Not Found" );
return;// Why return is needed here...???
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println( "Usage: ShowFile File" );
return;
}

do {
i = fin.read();
if(i != -1) System.out.print( (char) i);
} while(i != -1);

fin.close();

}
}

//FileInputStream fin;

Why the bold line gives an error stating that fin is not initialized???
Why the need for redundancy in:
FileInputStream fin = new FileInputStream(args[0]);
Also what purpose does the return statement have in a catch{} Block???
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The uninitialized error comes about because the compiler thinks you might get down to the read code without successfully initializing that variable to anything. You can make it go away by intializing to null, or by the syntax you showed. I like your way better - don't declare the variable even a line before you need to use it.

The return statements exit the method so none of the code following the catch block will execute. I guess I haven't seen that done in void methods before but it oughtta work.

This is curious code in that it catches two exception types but does not catch the IOExceptions. Is this from a teaching example somewhere? Bear in mind that most such examples try to illustrate one thing for the current lesson and may not actually be very good code in total. It looks like you already know not to accept everything you're handed. Keep asking questions!!
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prashanth,

Why the need for redundancy in:
FileInputStream fin = new FileInputStream(args[0]);

You can remove this line and uncomment the bold line.



Joyce
[ November 14, 2004: Message edited by: Joyce Lee ]
 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic