aspose file tools*
The moose likes Beginning Java and the fly likes FileInputStream Initialization... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FileInputStream Initialization..." Watch "FileInputStream Initialization..." New topic
Author

FileInputStream Initialization...

Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66
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???


Have A Nice Day !!!
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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!!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
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

Joined: Nov 13, 2004
Posts: 66
Thanks Stan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FileInputStream Initialization...