我正在开发一个独立于平台的应用程序。我收到一个文件 URL*。在 Windows 上,这些是:
tôi đang sử dụng new File(URI(urlOfDocument).getPath())
,它适用于第一个文件,也适用于 Unix、Linux、OS X,但不适用于 UNC 路径。
转换文件的标准方法是什么:URL 到 File(..) 路径,与 Java 6 兼容?
......
*注意:我从 OpenOffice/LibreOffice (XModel.getURL()) 收到这些 URL。
dựa trên Simone Giannis' answer 中提供的提示和链接,这是我的hackđể giải quyết vấn đề này.
我正在对 uri.getAuthority()
进行测试,因为 UNC 路径会报告授权。这是一个错误 - 所以我依赖一个错误的存在,这是邪恶的,但它似乎会永远存在(因为 Java 7 解决了 java.nio.Paths 中的问题)。
注意:在我的上下文中,我将收到绝对路径。我已经在 Windows 和 OS X 上对此进行了测试。
(仍在寻找更好的方法)
package com.christianfries.test;
nhập 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("____________________________________________________________");
}
}
Tôi là một lập trình viên xuất sắc, rất giỏi!