wood burning stoves 2.0*
The moose likes Performance and the fly likes FileNotFoundException or File.isFile()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Performance
Bookmark "FileNotFoundException or File.isFile()?" Watch "FileNotFoundException or File.isFile()?" New topic
Author

FileNotFoundException or File.isFile()?

Jiann-Luen Kow
Greenhorn

Joined: Mar 22, 2001
Posts: 8
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,
karl koch
Ranch Hand

Joined: May 25, 2001
Posts: 388
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

Joined: Mar 22, 2001
Posts: 8

Thank Karl for your explaination. I agree that exception is not a good way for flow control.
Jim Lang
Greenhorn

Joined: Oct 04, 2000
Posts: 27
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

Joined: May 25, 2001
Posts: 388
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
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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...


"I'm not back." - Bill Harding, Twister
Kirk Pepperdine
Author
Ranch Hand

Joined: Jan 17, 2001
Posts: 71
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.


Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0672324261/ref=jranch-20" target="_blank" rel="nofollow">Ant Developer's Handbook</a>
Scott Palmer
Ranch Hand

Joined: Jul 11, 2001
Posts: 31
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.
Peter Haggar
author
Ranch Hand

Joined: Jan 03, 2001
Posts: 106
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


Senior Software Engineer, IBM
author of: Practical Java
Jiann-Luen Kow
Greenhorn

Joined: Mar 22, 2001
Posts: 8

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.
 
Consider Paul's rocket mass heater.
 
subject: FileNotFoundException or File.isFile()?