TreePath到java.io.File [英] TreePath to java.io.File

查看:132
本文介绍了TreePath到java.io.File的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法来获取文件(或 java.nio.file.Path ,为此问题)来自 TreePath

Is there any easy way of getting a File (or java.nio.file.Path, for that matter) from a TreePath?

例如,你有一个 JTree 喜欢这样:

For example, you have a JTree like this:

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

如果您有 TreePath 转到 Black.jpg ,有没有办法获得路径<$的文件(或路径) c $ c> Green \Yellow\Black.jpg ?

If you have a TreePath going to Black.jpg, is there a way to get a File (or Path) with path Green\Yellow\Black.jpg?

我可以通过带父母/孩子的方式做到这一点通过一个并逐步构建路径,但我希望可能有一个更优雅的方式...

I can do it the long way, by taking parents/children one by one and constructing the path bit by bit, but I was hoping there might be a more elegant way...

推荐答案

你只需使用短正则表达式和 toString 方法就可以做到这一点,这是一个简单的例子:

You can do this pretty simply with a short regex and the toString method, heres a quick example:

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]

  1. tp.toString() - this calls the native to string method of an array, since that is the way TreePaths are represented under the covers. returns: [tmp, foo, bar]

replaceAll(\\] | | \\ [|,) - 这使用简单的正则表达式来替换字符 [] 并删除空格。字符 | 在JAVA的RegEx风格中意味着,所以这意味着如果我们遇到左括号,右括号或空格,将其替换为空字符串 返回 tmp,foo,bar

replaceAll("\\]| |\\[|", "") - this uses a simple regular expression to replace the characters [ and ] and also removes empty spaces. The character | means or in JAVA's flavor of RegEx, so this means "if we encounter a left bracket, right bracket or empty space, replace it the empty string." returns: tmp,foo,bar

.replaceAll(,,File.separator) - 最后一步,这将用本机文件路径分隔符替换逗号。 返回 tmp / foo / bar或tmp \ foobar

.replaceAll(",", File.separator) - the final step, this replaces commas with the native file path separator. returns: tmp/foo/bar or tmp\foobar

这篇关于TreePath到java.io.File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆