Java on Windows: banning '/' slash in file name to act as delimiter

I need to create a file based on the string provided to me. In this example, suppose the file name is "My file w / stuff.txt". When Java creates a file using

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

Although the default window separator is '\' , it assumes that the slash '/' is a file separator. So the next call to file.getName() will return " stuff.txt" . This causes problems for my program.

Is there a way to prevent this behavior?

+4
source share
4 answers

According to this Wikipedia page , Windows APIs process '/' as the equivalent of '\'. Therefore, even if you somehow enter "/" in the path component in the (for example) File object, there is a chance that Windows will at some point consider it as a path separator.

So your best options are:

  • Let Windows handle the "/" as usual; that is, allow processing of the character as a path separator.
  • As stated above, but with a warning to the user about '/'.
  • Check the characters '/' AND '\' and reject both claims that the file name (i.e. path component) cannot contain path separators.

(The best of the best depends on the details of your application, for example, whether you can report problems to the person who entered the fake file name.)

If you try to treat "/" differently than "\", you run the risk of creating more problems than you solve; for example, if your application needs to be scripted. If you quietly separate one or both characters (or turn them into something else), there is a risk that you will create additional problems; for example unexpected path conflicts.

(Initially, I suggested using the File(URL) constructor File(URL) on the β€œfile:” URL with the% -escaped '/' symbol. But even if this worked on the Java side, it will not work on the Windows side.)

+6
source

If you are given a string (from an external source), it does not look like you can prevent this string from containing certain characters. If you have some kind of graphical interface for creating a string, you can always limit it. Otherwise, any method that creates your file must check the slash and either return an error or handle it as it sees fit.

0
source

Since neither forward nor backslashes are allowed in Windows file names, they should be cleared from the lines used to indicate the files.

0
source

Ok, how could you stop it as a folder separator? This is a folder separator . If you could just decide for yourself what was and what was not a folder separator, then the whole system would crash down.

0
source

Source: https://habr.com/ru/post/1337695/


All Articles