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

本文介绍了一名开发者如何通过测试和错误检查来处理UNC路径(网络文件共享路径),使用Java的`URI`和`URL`类,特别针对Windows环境。作者分享了一个针对UNC路径的Hack方法,并提到了在不同操作系统上的测试结果。
摘要由CSDN通过智能技术生成

Christian Fr..

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值