您可以使用简短的正则表达式和
toString方法非常简单地执行此操作,以下是一个简单的示例:
TreePath tp = new TreePath(new String[] {"tmp", "foo", "bar"});String path = tp.toString().replaceAll("\]| |\[|", "").replaceAll(",", File.separator);File f = new File(path);// path is now tmpfoobar on Windows and tmp/foo/bar on unix编辑:解释
tp.toString()
-这将调用数组的本机到字符串方法,因为这是在底层表示TreePath的方式。 返回 :[tmp, foo, bar]
replaceAll("\]| |\[|", "")-使用简单的正则表达式替换字符[
,]
并删除空格。该字符|
表示 或具有 JAVA的RegEx风格,因此表示“ 如果遇到左括号,右括号或空白,请将其替换为空字符串” 。 返回 :tmp,foo,bar
.replaceAll(",", File.separator)-最后一步,用本地文件路径分隔符替换逗号。 返回 :tmp/foo/bar or tmpfoobar



