Question

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?

Was it helpful?

Solution

According to this Wikipedia page, the Windows APIs treat '/' as equivalent to '\'. So even if you somehow manage 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 best options are:

  • Let Windows treat the '/' as it would normally; i.e. let it treat the character as a pathname separator.
  • 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.

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

If you try to treat '/' differently from '\', you run the risk of creating more problems than you solve; e.g. if your application needs to be scripted. If you silently strip one or both characters (or turn them into something else) there is a risk that you will create further problems; e.g. unexpected pathname collisions.

(I originally suggested using the File(URL) constructor on a "file:" URL with a %-escaped '/' character. But even if that worked on the Java side, it won't work on the Windows side.)

OTHER TIPS

If a string is being provided to you (from an external source), it doesn't sound like you can prevent that string from containing certain characters. If you have some sort of GUI to create the string, then you can always restrict it there. Otherwise, whatever method is creating your file should check for a slash and either return an error or handle it as you see fit.

Since neither forward nor backward slashes are allowed in windows file names, they should be cleaned out of the Strings used to name files.

Well, how could you stop it being a folder separator? It is a folder separator. If you could just decide for yourself what was and what wasn't a folder separator, then the whole system would come crashing down.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top