-1

I need to map invalid characters to some other characters like "/" to "_" (forward slash to underscore) while creating a file because file name do not allowed to put slashes, question, double quotes etc.

Suppose I have

String name = "Message Test - 22/10/2016";

Now I want to write a file by using above string but it gives error because of slashes.

So I want to map slash like all the invalid characters to any other characters while writing a file. After writing, I need to read all the names of the files & show on the page.

SOMEHOW I MAP THE CHARACTERS, SO FILE NAME WOULD BE

Message_Test_-_22-10-2016

When I show it on web I need to return file name as the original name like

Message Test - 22/10/2016

I am using java. Can anyone help me out of this how can I start writing this approach or Is there any api for it or Is there any other approach.

I don't want to use database to co-related alias file name with original file name

Kushal Jain
  • 3,029
  • 5
  • 31
  • 48
  • 1
    I think you need to save your mappings anyhow. Imagine someone want to save a file named "Message_Test - 22-10-2016". You change the name to "Message_Test_-_22-10-2016". Without mapping it would be hard to find out, which _ you need to replace – Stefan Warminski May 23 '17 at 10:09

2 Answers2

0

I need to map invalid characters to some other characters like "/" to "_"

It is not enough robust since it supposes that you never use the _ character in the filename.
If you use it, how to know if a file stored as my_file should be displayed as my_file or my/file in your application.

I think that a more reliable way would be to have a file (JSON or XML for example) that stores the two properties for each file :

  • the stored filename
  • the visual name representing it in your application

It demands an additional file but it makes things really clearer.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Yes you right. But I have thousand or may be millions of files. Additional file will work ? – Kushal Jain May 23 '17 at 10:17
  • In this case, additional file would be a bad idea in terms of performance and memory consumption. You should use one mapping file by set of related files that should work together and this set of related files should have a fair size. I don't know your domain but if i take the parallel with the file system, it could be one mapping file by directory. – davidxxx May 23 '17 at 10:20
0

You can use a map to store the mappings:

E.g.

Map<Character,Character> map = new HashMap<Character,Character>();
map.put('/','_');

And then replace the characters in 1 traversal:

for(int i=0;i<str.length();i++){
  char c = str.charAt(i); 
  if( map.containsKey(c) )
    str.replace(c,map.get(c));
}
tryingToLearn
  • 10,691
  • 12
  • 80
  • 114