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:
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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With