How can I safely encode a string in Java to use as a filename? -
I am getting a string from the external process I want to use that string to make a filename, and Then typing that file is my code snippet to do this:
string s = ... // comes from external source file current file = new file (System.getProperty ("user. Home "), s); PrintWriter currentWriter = new print publisher (current file);
If there is an invalid character in it, like '/' in Unix-based OS, then a java.io.phileNotFoundException (right) has been thrown.
How can I safely convert the string to a symbol, so that it can be used as a filename?
Edit: What I'm hoping is an API call that does this for me.
I can do this:
string s = ... // External source file comes from file = new file (System.getProperty ("user.home" ), URLNcoder.X code (S, "UTF-8")); PrintWriter currentWriter = new print publisher (current file);
But I'm not sure that the URLNcoder is trusted for this purpose.
If you want to keep the result as the original file, SHA-1 or any other hashing scheme There is no answer but instead you want to do something like that.
char fileSep = '/'; // ... or make it portable four saved = '%'; // ... or some other legal four. String s = ... int len = s.length (); Stringbilder sb = new string builder (lane); For (int i = 0; i lt; '' || ch> = 0x7F || ch == fileSep || ... // adding other illegal characters || (ch == '.' And & amp; i == 0) / We do not want to bump with "." Or "..". Ch == escape) {sb.append (escape); If (f> 0x10) {sb.append ('0'); } Sb.append (integer tutorial (ch)); } Other {sb.append (ch); }} File current file = new file (System.getProperty ("user.home"), sb.toString ()); PrintWriter currentWriter = new print publisher (current file);
This solution returns a reversal encoding (with no collision) where the encoded string is similar to the original string in most cases. I am assuming that you are using 8-bit characters
The disadvantage of the URL encoder is that it encodes a whole number of legal file names.
If you do not want a guaranteed-to-reverse solution, just replace them with 'escape sequences' instead of 'bad' characters.
Comments
Post a Comment