我正在开发一个独立于平台的应用程序。我正在接收一个文件URL*。在windows上,它们是:
file:///Z:/folder%20to%20file/file.txt
file://host/folder%20to%20file/file.txt
( UNC路径)(UNC路径)
我使用的是new File(URI(urlOfDocument).getPath())
,它在第一个版本上运行得很好,在Unix、Linux、OS上也运行得很好,但不能在UNC路径上运行。
将file: URLs转换为File(..)的标准方法是什么?路径,是否与Java 6兼容?
.
*注意:我正在从OpenOffice / LibreOffice (XModel.getURL())收到这些URL。
发布于 2013-08-30 16:50:30
根据Simone Giannis answer中提供的提示和链接,这是我修复此问题的方法。
我正在测试uri.getAuthority(),因为UNC path将报告一个授权。这是一个bug -所以我依赖于bug的存在,这是邪恶的,但它看起来好像永远都会存在(因为Java7解决了java.nio.Paths中的问题)。
注意:在我的上下文中,我将接收绝对路径。我已经在Windows和OS上测试过了。
(仍在寻找更好的方法)
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("____________________________________________________________");
}
}
发布于 2017-10-17 23:06:58
基于@SotiriosDelimanolis的注释,这里有一个处理URL的方法(如file:...)和非URL(如C:...),使用Spring: FileSystemResource:
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);
}
}
发布于 2013-08-30 07:55:06
Java (至少5条和6条,java 7路径解决得最多)在UNC和URI方面存在问题。Eclipse团队在这里做了总结:http://wiki.eclipse.org/Eclipse/UNC_Paths
在java.io.File javadoc中,UNC前缀是“/”,java.net.URI处理file:////host/path (四个斜杠)。
有关为什么会发生这种情况以及它在其他URI和URL方法中可能导致的问题的更多详细信息,可以在上面给出的链接末尾的bug列表中找到。
使用这些信息,Eclipse团队开发了org.eclipse.core.runtime.URIUtil类,它的源代码在处理UNC路径时可能会有所帮助。
https://stackoverflow.com/questions/18520972
复制相似问题