TreePath到java.io.File

有没有简单的方法从TreePath获取File (或java.nio.file.Path )?

例如,你有一个像这样的JTree

 Green |---Blue |---Red |---Yellow |---Purple.jpg |---Brown.jpg |---Black.jpg 

如果您有一个TreePath转到Black.jpg ,有没有办法获得路径为Green\Yellow\Black.jpgFile (或Path )?

我可以做很长的路,一个接一个地带着父母/孩子,一点一点地构建路径,但我希望有更优雅的方式……

你可以用一个简短的正则表达式和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 tmp\foo\bar on Windows and tmp/foo/bar on unix 

编辑:解释

  1. tp.toString() – 这会调用数组的native to string方法,因为这是TreePaths在封面下的表示方式。 返回[tmp, foo, bar]

  2. replaceAll("\\]| |\\[|", "") – 这使用一个简单的正则表达式来替换字符[] ,并删除空格。 人物| 意思是JAVA的RegEx风格,所以这意味着“ 如果我们遇到左括号,右括号或空格,请将空字符串替换掉 。” 返回tmp,foo,bar

  3. .replaceAll(",", File.separator) – 最后一步,它用本机文件路径分隔符替换逗号。 返回tmp/foo/bar or tmp\foobar

我认为你坚持制作自己的方法。

 public static String createFilePath(TreePath treePath) { StringBuilder sb = new StringBuilder(); Object[] nodes = treePath.getPath(); for(int i=0;i