Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked exceptions and File.exists() in Java

Tags:

java

I have primarily a C# background (and am very much a newbie) so forgive me if my assumptions based on this are the problem.

Simply put, one of the features in a piece of software I'm working on (in Java) has the user input a file name. What I intend to do is have the program loop and append a string to the end of the file name from an array of possible append strings, to see if a file exists, and if it does, open it. I am guaranteed to have only ONE file of a given name, so breaking out of the loop on the first success isn't a bug (if the file name the user specifies is "foo" and the appendStrings array has "bar" and "baz" inside of it, I am guaranteed there will never be both a "foobar" and "foobaz" in the directory). What I eventually came up with was similar to this:

public FileReader LocateFile(String fileName)
{
    FileReader toReturn = null;
    for(int i = 0; i < appendStrings.length; i++)
    {
        File locatedFile = new File(fileName + appendStrings[i]);
        try
        {
            toReturn = new FileReader(locatedFile);
        }
        catch(FileNotFoundException ex)
        {
            continue;
        }
    }
    //...handling in case I didn't find a file.
}

Great, it works just fine. Except for two problems:

  1. The compiler is upset with me that I'm declaring a variable (ex) that I'm not using. I suppose I could log the exception or something, but that seems ridiculous because this will happen often and I'd rather not fill my log file with excessive noise just to make the compiler happy.
  2. I've read from countless sources that you don't use exceptions to control the flow of the program; you use them for exceptional circumstances.

My question is: is there a way to please the compiler in this situation? I have to catch that FileNotFoundException, so using File.exists() won't really solve my problem. Am I doing things backwards, or is this just how Java rolls?

like image 294
Sepulchritude Avatar asked May 11 '26 20:05

Sepulchritude


1 Answers

You are right, you shouldn't use exceptions to control your program flow.

You have already written the algo in plane strings just convert it into java code.

public FileReader LocateFile(String fileName)
{
    FileReader toReturn = null;
    for(int i = 0; i < appendStrings.length; i++)
    {
        File locatedFile = new File(fileName + appendStrings[i]);
         if(locatedFile.exists()) {
             toReturn = new FileReader(locatedFile);
             break;
        }
    }
    //...handling in case I didn't find a file.
}
like image 66
Ankit Bansal Avatar answered May 13 '26 10:05

Ankit Bansal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!