Case sensitive file extension and existence checking

后端 未结 3 690
遥遥无期
遥遥无期 2021-01-25 08:55

I need to check whether or not a file exists. Which can be accomplished by File#exists() method. But this existence checking is case sensitive. I mean if I have a f

相关标签:
3条回答
  • 2021-01-25 09:17

    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.

    0 讨论(0)
  • 2021-01-25 09:33

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-25 09:35

    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)
    
    0 讨论(0)
提交回复
热议问题