0

How do you sanitize string to make sure it will be valid to be used as a directory name?

I have tried searching as well, but can't find good information what characters are good or not to be used as directory name.

johnvantes
  • 29
  • 7
  • @BlackFrog my question is for directory name, while those link are for file name, are the same rules applies for both? – johnvantes Jan 10 '16 at 17:39
  • Directory names and file names have the same restriction. There is no difference. – Black Frog Jan 10 '16 at 17:41
  • @johnvantes In my opinion you should rethink what you're trying to do. It's not good to try to fix a path that has been given to you wrong, how can you possibly trust any of the characters of a wrong path ? Don't try to recover from failure, fail safe (message) or fail hard (exception) – Dici Jan 10 '16 at 17:42

2 Answers2

0

Id use ASCII values 48 - 57, and 97-122 (you can use capital letters too if you expect users to look at the directory paths) in order to be completely safe.

aiguy
  • 671
  • 5
  • 20
-4

Simply by trying to create it :

File directory = new File(path);
directory.mkdirs();

If it fails, it will throw an exception that you can handle appropriately.

Dici
  • 25,226
  • 7
  • 41
  • 82
  • thanks, but my question would be what to do if the trial is failing. – johnvantes Jan 10 '16 at 17:29
  • Totally depends on your application, what should it do ? – Dici Jan 10 '16 at 17:30
  • It should then sanitize the failing `path` string so that it will be a valid directory name. – johnvantes Jan 10 '16 at 17:36
  • That sounds like a pretty bad idea. How do you sanitize `gre*--\\//*..02fezfgoçà"\\è-$ù!` ? You should not try to recover from this, either you print an error message or you just fail – Dici Jan 10 '16 at 17:38
  • Hmm. You have a good point. This is what my app does. It loads a video. Then it produces images based on that. Then it automatically saves the produced images on a directory with a name based on the video name. Therefore I need to sanitize the video name. – johnvantes Jan 10 '16 at 17:48
  • I see. I think the only unallowed character is the slash. My answer is not particularly good for your use case as it might do weird things with a name like `na/me`. Is the name the only part of the path you don't have control over ? By the way if the video already exists as a file on the device, then you know its name is valid – Dici Jan 10 '16 at 18:00
  • Yes, as the directory name should be automatically generated. _By the way if the video already exists as a file on the device, then you know its name is valid_ thanks! – johnvantes Jan 11 '16 at 13:27
  • Do the comments answer the question ? If so, I will edit my answer to reflect this. Otherwise, do you stll need to solve this issue ? – Dici Jan 11 '16 at 20:04