Search code examples
javawindowsfileslash

Java on Windows: prevent '/' slash in file name from acting as a separator


I have to create a file based on a string provided to me. For this example, let's say the file name is "My file w/ stuff.txt". When Java creates the file using

 File file = new File("My file w/ stuff.txt")

Even though the default windows separator is '\', it assumes that the '/' slash is a file separator. So a future call to file.getName() would return " stuff.txt". This causes problems for my program.

Is there any way to prevent this behaviour?


Solution

  • According to this Wikipedia page, the Windows APIs treat / as equivalent to \. Even if you somehow managed to embed a / in a pathname component in (for example) a File object, the chances are that Windows at some point will treat it as a path separator.

    So your options are:

    • Let Windows treat the / as it would normally; i.e. let it treat the character as a pathname separator. (Users should know this. It is a "computer literacy" thing ... for Windows users.)

    • As above, but with a warning to the user about the /.

    • Check for / AND \ characters, and reject both saying that a filename (i.e. a pathname component) cannot contain pathname separators.

    • Use some encoding scheme to encode reserved characters before attempting to create the files. You must also then apply the (reverse) decoding scheme at all points where you need to show the user their "file name with slashes".

      Note: if the user can see the actual file paths (e.g. via a command shell) you can't hide the encoding / decoding from them. Arguably, that is worse than the "problem" you were trying to solve in the first place.

      There is no escaping scheme that the Windows OS will accept for this purpose. You would need to use something like % encoding; e.g. replace / with %2F. Basically you need to "hide" the slash character from Windows by replacing it with other characters in the OS-level pathname!

    The best option depends on details of your application; e.g. whether you can report problems to the person who entered the bogus filename.