• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

FileNotFoundException or File.isFile()?

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I would like to know which of the following is efficient to handle:
First way:
----------
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(file);
} catch (FileNotFoundException ex) {
InputStream is = ClassLoader.getSystemAsResource
(file.getPath());
reader = new InputStreamReader(is);
}
Here file is an instance of File class. The path of the file
may come in the form of directory in user's directory
"D:\JDK1.3" or in the form of "com/borland/xxx/myFile.txt"
The latter form, which I know of is for getting a file in a
Jar file.
Second way:
-----------
InputStreamReader reader = null;
if (file.isFile())
{
reader = new InputStreamReader(new FileInputStream(file));
}
else
{
InputStream is = ClassLoader.getSystemAsResource(
file.getPath());
reader = new InputStreamReader(is);
}
Even the second way will throws a FileNotFoundException which
which must be caught, I just pass up to the calling method. I
wanted to look for files that may reside either in user's
working directory or in the jar files. Which is the correct
form in handling this case?
Thanks in advance,
 
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
dont use exceptions for flow control (is also the title of chapter in a javabook - i dont remember the title).
use the canRead(), isFile(), isDirectory() and whatsoever methods if you can.
did you consider the list methods from File ? you get a File[] containing all the Files in a Parent File (all real Files and all Directories). There is also a list method which takes an FileFilter as argument. you can Write a very simple FileFilter by yourself which only accepts real Files (confusing these names. everithing is File....)

karl
 
Jiann-Luen Kow
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Thank Karl for your explaination. I agree that exception is not a good way for flow control.
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why shouldn't you use exceptions for flow control? that's like saying 'don't use exceptions, code everything procedurally within your classes'.
I'm interested to find out the reasoning behind this 'directive'.
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
jim,
well sure you can do it the other way. i just think that using exception for flow control is not that nice. for me exceptions are something that should not occur in normal program flow.

karl
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim- I think there are two basic reasons.
1. From a performance standpoint, it takes a certain amount of time to create an Exception object, throw it, and catch it. In many cases there are other alternatives which would allow you to check something beforehand to see if the exception is going to occur. The classic example here is:
<code><pre>
try {
while (true) {
char c = input.read();
output.write(c);
}
}
catch (EOFException e) {}
</pre></code>
It's certainly possible to write a loop this way - but it will be more efficient in the long run to check for the end of input as you go, rather than depending on the exception:
<code><pre>
char c;
while ((c = input.read()) >= 0) {
output.write(c);
}
</pre></code>
2. From a readability standpoint, other programmers will usually expect to see the standard, expected logical flow of your program spelled out with standard control structures - if/else and loops. Exception handling logic is usually a bit harder to read, and most people use it only for the unusual, unexpected cases. In the first example above, another programmer looking at the code for the first time might well think that the loop is intended to execute forwever (i.e. for the life of the program). They'll probably work it out eventually, but the coding style creates needless confusion. The second example on the other hand communicates more directly that once the input stream ends, the loop ends.
Hope that helps...
 
Author
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exception handling may not be a desirable form of flow control but, none the less, it is flow control. In the above examples, at some point, the cost of performing the check for EOF will be greater than the cost of throwing the exception. Thus, I would argue that it is acceptable to throw the exception if you're processing large files and removing the check results in a significant performance improvement.
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I disagree that the performance improvement would be significant and in any case it would depend heavily on the JVM.
At one point on some JVMs it was faster to write some loops that processed data in an array and terminated the loop by catching the array index out of bounds exception, but then JVMs matured and that method became slower. That sort of optimization is poor style in my opinion, and in the long run it simply isn't worth it. Don't try to trick the JVM it will only backfire on you. The optimizations done on future JVMs will be based on running properly strucured code, not some 'clever' hack.
 
author
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the tests I have done, the only way I got faster code using the exception trick was when I ran the loop for a lot of iterations (ie. 10 million) AND when I ran without the JIT enabled. Running with the JIT, the code with the exception trick was the same.
Therefore, I would only ever consider this trick if I absolutely knew it provided an improvement on my system (ie. my VM didn't have a JIT and I profiled it), and I needed the speed up.
Here's some code I use:

Invode the code with:
java excperfTest 10000000 (runs with the JIT)
and
java -Djava.compiler=NONE excperfTest 10000000 (runs without JIT)
Peter Haggar
------------------
Senior Software Engineer, IBM
author of: Practical Java
 
Jiann-Luen Kow
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I gave a thought on this subject after I posted this message, I remember reading one of the feature of Exception Handling is to force the programmer to catch the exception in the OO way. While on the other hand, doing this in procedural language like C or Cobol, one would either ignore to check for exception like 'if file exist and fail miserably', or just pass up the error/exception up to its calling function without the cleaning up. What I think is that giving the situation where you have exceptions thrown from a method you interested to call, isn't it better to have a try-catch block as this is the right OO ways. That is why this feature came out to replace the procedural language's defect on handling errors.
Performance is a big issue if you are dealing a lot on the method, but if I am only calling it once in a while, I guess a try-catch block is better understandable.
 
I wasn't selected to go to mars. This tiny ad got in ahead of me:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic