如何安全地用Java对字符串进行编码以用作文件名?
我从外部进程接收字符串。我想使用该字符串创建文件名,然后写入该文件。以下是我的代码片段:
String s = ... // comes from external source
File currentFile = new File(System.getProperty("user.home"), s);
PrintWriter currentWriter = new PrintWriter(currentFile);
如果 s 包含无效字符,例如基于 Unix 的操作系统中的 “/”,则 (正确地) 抛出 java.io.FileNotFoundException。
如何安全地对字符串进行编码,以便将其用作文件名?
编辑:我希望的是一个API调用,它可以为我做到这一点。
我可以这样做:
String s = ... // comes from external source
File currentFile = new File(System.getProperty("user.home"), URLEncoder.encode(s, "UTF-8"));
PrintWriter currentWriter = new PrintWriter(currentFile);
但我不确定URLEncoder是否可靠。