简体   繁体   English

TreePath到java.io.File

[英]TreePath to java.io.File

Is there any easy way of getting a File (or java.nio.file.Path , for that matter) from a TreePath ? 是否有任何简单的方法可以从TreePath中获取File (或java.nio.file.Path )?

For example, you have a JTree like this: 例如,您有一个像这样的JTree

Green
|---Blue
|---Red
|---Yellow
    |---Purple.jpg
    |---Brown.jpg
    |---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 ? 如果您有一个TreePath转到Black.jpg ,是否可以通过路径Green\\Yellow\\Black.jpg获取File (或Path )?

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... 我可以做一个很长的路要走,一个接一个地带父母/孩子,并一点一点地构建路径,但是我希望可以有一种更优雅的方式...

I think your stuck with making your own method. 我认为您坚持使用自己的方法。

public static String createFilePath(TreePath treePath) {
    StringBuilder sb = new StringBuilder();
    Object[] nodes = treePath.getPath();
    for(int i=0;i<nodes.length;i++) {
        sb.append(File.separatorChar).append(nodes[i].toString()); 
    } 
    return sb.toString();
}

You can do this pretty simply with a short regex and the toString method, heres a quick example: 您可以使用简短的正则表达式和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

EDIT: Explanation 编辑:解释

  1. tp.toString() - this calls the native to string method of an array, since that is the way TreePaths are represented under the covers. tp.toString() -这将调用数组的字符串本机方法,因为这是TreePath在tp.toString()表示的方式。 returns : [tmp, foo, bar] 返回 [tmp, foo, bar]

  2. replaceAll("\\\\]| |\\\\[|", "") - this uses a simple regular expression to replace the characters [ and ] and also removes empty spaces. replaceAll("\\\\]| |\\\\[|", "") -这使用一个简单的正则表达式来替换字符[] ,并删除空格。 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 ." 表示或具有 JAVA的RegEx风格,因此表示“ 如果遇到左括号,右括号或空白,请将其替换为空字符串 。” returns : tmp,foo,bar 返回 tmp,foo,bar

  3. .replaceAll(",", File.separator) - the final step, this replaces commas with the native file path separator. .replaceAll(",", File.separator) -最后一步,用本地文件路径分隔符替换逗号。 returns : tmp/foo/bar or tmp\\foobar 返回 tmp/foo/bar or tmp\\foobar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM