是否有任何方法来转义路径字符串中的空格,大括号和其他字符?

时间:2016-08-19 16:05:19

标签: java

我希望能够在路径字符串中转义符号,这样我就可以将它传递给没有引号的bash。

即。我有一个文件sample (1).txt

我想将此字符串转换为sample\ \(1\).txt。空格和大括号是符号的一个例子,应该明确地进行转义。

我想使用一个方法来转义所有应该转义的字符。

也许在默认库或其他一些流行的库中有一个。

3 个答案:

答案 0 :(得分:0)

您可以使用String.replace()方法在特殊字符之前包含或删除任何字符。

答案 1 :(得分:0)

查看Pattern / Matcher / StringBuffer类:

Pattern p = Pattern.compile("([ ()])"); //regex setup
Matcher m = p.matcher("replace these spaces (2).txt"); //sample input
StringBuffer s = new StringBuffer();
while (m.find())
    m.appendReplacement(s, "\\\\" + m.group(1));
m.appendTail(s); //add the last tail of code
System.out.println(s.toString());

在main中运行的示例输出:

// replace\ these\ spaces\ \(2\).txt

答案 2 :(得分:0)

您没有说明选择哪些字符是符号的标准,但假设您想要一些可以转换为URI的内容,则提供了java类java.io.File和接口java.io.Path这个原因(以及其他一些原因)。

这是java 7+版本:

// toASCIIString is not usually necessary
String withoutSymbols = new java.io.File("sample (1).txt").toUri().toASCIIString();