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:

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