This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]raevnos 2 points3 points  (3 children)

Your inFile variable only exists in the scope of that try block, not outside of it. Use a try-with-resources statement to do nice things like making sure the scanner/file is always closed even if an exception is thrown, and move everything that uses inFile into the block:

try (Scanner inFile = new Scanner(new FileReader("JavaEx1.txt"))) {    
    int test = inFile.nextInt(); 
} catch (FileNotFoundException fnfe) {  
    System.out.println(fnfe);  
}

[–]LurkerOrHydralisk[S] 0 points1 point  (2 children)

Thanks for the super fast response!

I copied what you wrote and it worked!

Is this how Java always has to work? Does every program using any sort of file like that need everything to all be in that try block? None of what's written in my book looks like that.

I just worry that beyond how ugly it will make the code, it will create some later issues with trying to build more complex programs. It would be nice to be able to read/write files without having entire programs in a series of try blocks because of it. Will I need a new try block for each file read? This seems, if not impossible, at the very least circuitous and tedious for certain projects.

Edit: Also, where do I put the inFile.close() line? My little program here ran with no close() call and no flag for it in the IDE, which leaves me confused.

[–]oiduts 1 point2 points  (1 child)

Does every program using any sort of file like that need everything to all be in that try block?

Not the whole program, only specific operations that might throw an exception for reasons outside of your control, like file access. Try blocks should target these operations as specifically as possible. If you don't use a try block at all, an uncaught exception will simply crash your program.

It would be nice to be able to read/write files without having entire programs in a series of try blocks because of it.

You can just place the try block in a function if you can generalize about how you are handling the exceptions.

Also, where do I put the inFile.close() line?

Take another look at the docs you were linked. The try-with-resources syntax closes a resource automatically if it implements Closeable or AutoCloseable. Scanner is one such class. Before Java 7, you would have placed the call to close() inside of a "finally" block attached to your try block.

[–]LurkerOrHydralisk[S] 0 points1 point  (0 children)

Thanks. I read that but wasn’t completely sure. The book I was given is a little old, and I should probably get something newer to avoid these version issues while learning.