Christian Fr..
11
基于对西蒙娜Giannis答案提供的提示和链接,这是我砍来解决这个问题.
我正在测试uri.getAuthority(),因为UNC路径将报告一个权威.这是一个错误 - 所以我依赖于一个错误的存在,这是邪恶的,但它似乎将永远存在(因为Java 7解决了java.nio.Paths中的问题).
注意:在我的上下文中,我将收到绝对路径.我在Windows和OS X上测试了这个.
(仍在寻找更好的方法)
package com.christianfries.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class UNCPathTest {
public static void main(String[] args) throws MalformedURLException, URISyntaxException {
UNCPathTest upt = new UNCPathTest();
upt.testURL("file://server/dir/file.txt"); // Windows UNC Path
upt.testURL("file:///Z:/dir/file.txt"); // Windows drive letter path
upt.testURL("file:///dir/file.txt"); // Unix (absolute) path
}
private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
URL url = new URL(urlString);
System.out.println("URL is: " + url.toString());
URI uri = url.toURI();
System.out.println("URI is: " + uri.toString());
if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
// Hack for UNC Path
uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
}
File file = new File(uri);
System.out.println("File is: " + file.toString());
String parent = file.getParent();
System.out.println("Parent is: " + parent);
System.out.println("____________________________________________________________");
}
}