Case sensitive file extension and existence checking

五迷三道 提交于 2019-12-02 04:39:18

You could get the file names in a folder with

File.list() 

and check names by means of

equalsIgnoreCase()

Or try http://commons.apache.org/io/ and use

FileNameUtils.directoryContains(final String canonicalParent, final String canonicalChild)

This way I had solved the problem:

public String getActualFilePath() {
    File givenFile = new File(filePath);
    File directory = givenFile.getParentFile();

    if(directory == null || !directory.isDirectory()) {
        return filePath;
    }


    File[] files = directory.listFiles();
    Map<String, String> fileMap = new HashMap<String, String>();

    for(File file : files) {                        
        if(file.isDirectory()){
            continue;
        }

        String absolutePath = file.getAbsolutePath();
        fileMap.put(absolutePath, StringUtils.upperCase(absolutePath));
    }

    int noOfOcc = 0;
    String actualFilePath = "";

    for(Entry<String, String> entry : fileMap.entrySet()) {
        if(filePath.toUpperCase().equals(entry.getValue())) {
            actualFilePath = entry.getKey();
            noOfOcc++;
        }
    }

    if(noOfOcc == 1) {
        return actualFilePath;
    }

    return filePath;
}

Here filePath is the full path to the file.

The canonical name returns the name with case sensitive. If it returns a different string than the name of the file you are looking for, the file exists with a different case.

So, test if the file exists or if its canonical name is different

public static boolean fileExistsCaseInsensitive(String path) {
    try {
        File file = new File(path);
        return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
    } catch (IOException e) {
        return false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!