views:

496

answers:

2

I have a file path in String form. In Java, I need to determine if that file exists on the file system (and our code needs to be cross-platform as it runs on Windows, Linux and OS X).

The problem is that the case of the file path and the file itself may not match, even though they do represent the same file (presumably this is because they originated on Windows and the discrepancy was not noticed).

For example, I have a file path of "ABC.txt". A file called "abc.txt" exists on the file system. The following code will return true on Windows but false on Linux:

new File("ABC.txt").exists();

What is the best way to determine if the file exists, and if it exists to return a handle to the file on the file system?

+4  A: 

Get the list of files from the directory (File.list()) and compare the names using equalsIgnoreCase().

Shimi Bandiel
Yes that's a possbility, but the problem still exists if directories in the path are the wrong case. The solution might end up being some kind of recursive algorithm that goes up the directory tree doing case-insensitive searches. But I'm hoping for a better solution!
jwaddell
@jwaddell: i don't think there is a better solution since the filename/path can be in any casing and the linux os treats it in a case sensitive mode.
Shimi Bandiel
Looks like I'll reluctantly implement this solution, plus recursive path checking.
jwaddell
A: 

If the discrepancies are random, then to me Shimi's solution including recursive path segment checking is the best solution. It sounds ugly at a first glance but you can hide the magic in a separate class and implement a simple API to return the file handle for a given file name, so you just see something like a Translator.translate(file) call.

Maybe, the discrepancies are kind of static, predictable. Then I would prefer a dictionary that can be used to translate a given file name to Windows/Linux file names. This has on big advantage over the other method: the risk to get a wrong file handle is smaller.

If the dictionary was really static, you could create and maintain a properties file. If it was static but more complex, say a given file name could be translated to more than one possible target file names, I'd back up the dictonary class with a Map<String, Set<String>> datastructure (Set preferred over List because there are no duplicate alternates).

Andreas_D
Unfortunately the file names could be anything.
jwaddell