将Java file:// URL转换为File(...)路径,与平台无关,包括UNC路径

Chr*_*ies 25 java windows url

我正在开发独立于平台的应用程序.我收到一个文件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路径.

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

......

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

Chr*_*ies 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("____________________________________________________________");
    }

}
Run Code Online (Sandbox Code Playgroud)


Mar*_*idt 7

基于@SotiriosDelimanolis 的评论,这里有一种使用 Spring 的 FileSystemResource 处理 URL(例如 file:...)和非 URL(例如 C:...)的方法:

public FileSystemResource get(String file) {
    try {
        // First try to resolve as URL (file:...)
        Path path = Paths.get(new URL(file).toURI());
        FileSystemResource resource = new FileSystemResource(path.toFile());
        return resource;
    } catch (URISyntaxException | MalformedURLException e) {
        // If given file string isn't an URL, fall back to using a normal file 
        return new FileSystemResource(file);
    }
}
Run Code Online (Sandbox Code Playgroud)


Sim*_*nni 1

Java(至少5和6,java 7路径解决了大部分)有UNC和URI的问题。Eclipse 团队将其总结如下:http://wiki.eclipse.org/Eclipse/UNC_Paths

在 java.io.File javadocs 中,UNC 前缀是“////”,而 java.net.URI 处理 file:////host/path(四个斜杠)。

有关发生这种情况的原因以及它在其他 URI 和 URL 方法中可能导致的问题的更多详细信息,请参阅上面给出的链接末尾的错误列表。

使用这些信息,Eclipse 团队开发了 org.eclipse.core.runtime.URIUtil 类,该类的源代码在处理 UNC 路径时可能会有所帮助。