[英]TreePath to 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.jpg
獲取File
(或Path
)?
我可以做一個很長的路要走,一個接一個地帶父母/孩子,並一點一點地構建路徑,但是我希望可以有一種更優雅的方式...
我認為您堅持使用自己的方法。
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();
}
您可以使用簡短的正則表達式和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
編輯:解釋
tp.toString()
-這將調用數組的字符串本機方法,因為這是TreePath在tp.toString()
表示的方式。 返回 : [tmp, foo, bar]
replaceAll("\\\\]| |\\\\[|", "")
-這使用一個簡單的正則表達式來替換字符[
和]
,並刪除空格。 人物|
表示或具有 JAVA的RegEx風格,因此表示“ 如果遇到左括號,右括號或空白,請將其替換為空字符串 。” 返回 : tmp,foo,bar
.replaceAll(",", File.separator)
-最后一步,用本地文件路徑分隔符替換逗號。 返回 : tmp/foo/bar or tmp\\foobar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.