How can I safely encode a string in Java to use as a filename?

后端 未结 9 2031
失恋的感觉
失恋的感觉 2020-11-29 22:53

I\'m receiving a string from an external process. I want to use that String to make a filename, and then write to that file. Here\'s my code snippet to do this:



        
9条回答
  •  死守一世寂寞
    2020-11-29 23:20

    It depends on whether the encoding should be reversible or not.

    Reversible

    Use URL encoding (java.net.URLEncoder) to replace special characters with %xx. Note that you take care of the special cases where the string equals ., equals .. or is empty!¹ Many programs use URL encoding to create file names, so this is a standard technique which everybody understands.

    Irreversible

    Use a hash (e.g. SHA-1) of the given string. Modern hash algorithms (not MD5) can be considered collision-free. In fact, you'll have a break-through in cryptography if you find a collision.


    ¹ You can handle all 3 special cases elegantly by using a prefix such as "myApp-". If you put the file directly into $HOME, you'll have to do that anyway to avoid conflicts with existing files such as ".bashrc".
    public static String encodeFilename(String s)
    {
        try
        {
            return "myApp-" + java.net.URLEncoder.encode(s, "UTF-8");
        }
        catch (java.io.UnsupportedEncodingException e)
        {
            throw new RuntimeException("UTF-8 is an unknown encoding!?");
        }
    }

提交回复
热议问题