-- Leo's gemini proxy

-- Connecting to republic.circumlunar.space:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini

Checking the case of a filename on Windows


Windows generally uses a case-insensitive but not case-preserving file system.


When writing some code that is intended to be used on Linux as well as Windows, I wanted it to fail on Windows in the same cases that it would fail on Linux, and this meant detecting when the case of a filename differed from its canonical case on the file system.


case-insensitive but not case-preserving


I want to ask "is this file name correct in terms of case?"


I was working in Java, but I think this issue would be similar in other languages: it's difficult to ask for the canonical case version of a file name when we currently have a filename with abitrary case.


The only solution I came up with was to list the contents of the parent directory and check whether my arbitrary filename is listed with the correct case in the results:


// CaseCheck.java

import java.util.Arrays;
import java.io.File;
import java.io.IOException;

class CaseCheck
{
   private static File parentFile( File f )
   {
       File ret = f.getParentFile();
       if ( ret == null )
       {
           ret = new File( "." );
       }
       return ret;
   }

   private static boolean existsAndCaseCorrect( String fileName )
   {
       File f = new File( fileName );
       return Arrays.asList( parentFile( f ).list() ).contains( f.getName() );
   }

   public static void main( String[] args ) throws IOException
   {
       System.out.println( existsAndCaseCorrect( args[0] ) );
   }
}


Checking it on its own source file:


javac CaseCheck.java && java CaseCheck cASEcheck.java
false

javac CaseCheck.java && java CaseCheck CaseCheck.java
true


It seems to work.


Note that this also returns false if the file doesn't exist, and will throw an error if the file name specifies a parent directory that doesn't exist.


Originally posted at 2013-05-23 11:30:22+00:00. Automatically generated from the original post : apologies for the errors introduced.


original post

-- Response ended

-- Page fetched on Sun May 19 06:35:47 2024