TreePath to java.io.File

非 Y 不嫁゛ 提交于 2019-12-02 11:32:42

问题


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

For example, you have a JTree like this:

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?

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...


回答1:


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

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. returns: [tmp, foo, bar]

  2. 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

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




回答2:


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();
}


来源:https://stackoverflow.com/questions/20364571/treepath-to-java-io-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!