gpt4 book ai didi

java - 转换 Java 文件 ://URL to File(. ..) 路径,独立于平台,包括 UNC 路径

转载 作者:IT老高 更新时间:2023-10-28 20:42:05 32 4
gpt4 key购买 nike

我正在开发一个独立于平台的应用程序。我收到一个文件 URL*。在 Windows 上,这些是:

  • file:///Z:/folder%20to%20file/file.txt

  • file://host/folder%20to%20file/file.txt(UNC 路径)

我正在使用 new File(URI(urlOfDocument).getPath()),它适用于第一个文件,也适用于 Unix、Linux、OS X,但不适用于 UNC 路径。

转换文件的标准方法是什么:URL 到 File(..) 路径,与 Java 6 兼容?

......

*注意:我从 OpenOffice/LibreOffice (XModel.getURL()) 收到这些 URL。

最佳答案

基于 Simone Giannis' answer 中提供的提示和链接,这是我的hack来解决这个问题。

我正在对 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 - 转换 Java 文件 ://URL to File(. ..) 路径,独立于平台,包括 UNC 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18520972/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com