java file 转URL,将Java file:// URL转换为File(...)路径,独立于平台,包括UNC路径...

I am developing a platform independent application. I am receiving a file URL*.

On windows these are:

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

file://host/folder%20to%20file/file.txt (an UNC path)

I am using new File(URI(urlOfDocument).getPath())which works fine with the first one and also on Unix, Linux, OS X, but does not work with UNC paths.

What is the standard way to convert file: URLs to File(..) paths, being compatible with Java 6?

......

*

Note: I am receiving theses URLs from OpenOffice / LibreOffice (XModel.getURL()).

解决方案

Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.

I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).

Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.

(Still looking for a better way to do it)

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("____________________________________________________________");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值