Case-insensitive File.equals on case-sensitive file system

jwaddell picture jwaddell · Aug 19, 2009 · Viewed 18.5k times · Source

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?

Answer

Shimi Bandiel picture Shimi Bandiel · Aug 19, 2009

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