根据Simone 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("____________________________________________________________");
}
}
尝试的Java 7'Paths.get(新网址(URL).toURI());' –
感谢(+1)为指向java.nio.Paths。但是,我需要与Java 6兼容(我编辑问题) - 对不起。 –
标准的方法是'new File(url.toURI())'。即使使用Java 5也是如此。 – Holger