TreePath to java.io.File

后端 未结 2 1090
执念已碎
执念已碎 2021-01-25 10:58

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 JT

2条回答
  •  有刺的猬
    2021-01-25 11:44

    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

提交回复
热议问题