URI以及配合JAVA中的File的使用

URI的组成

在这里插入图片描述
从上面我们可以看出来URI中的组成部分,其实也与URL高度相似,因为URL是URI的子集嘛。

在配合Java中的File使用的时候需要注意,java中的File对URI的组成部分进行了严格的限制,如果满足就会出现异常,具体请看。
这是API文档中的说明

uri - An absolute, hierarchical URI with a scheme equal to “file”, a non-empty path component, and undefined authority, query, and fragment components
这是代码中的实现

public File(URI uri) {

    // Check our many preconditions
    if (!uri.isAbsolute())
        throw new IllegalArgumentException("URI is not absolute");
    if (uri.isOpaque())
        throw new IllegalArgumentException("URI is not hierarchical");
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
        throw new IllegalArgumentException("URI scheme is not \"file\"");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("URI has an authority component");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("URI has a fragment component");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("URI has a query component");
    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");

    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}

上面这是File的构造方法,这也就是我之前使用的时候一直出现问题的原因。
我之前些的URI

file://D:/tomcat/webapps

上面这个会出现什么问题呢?问题就在于因为file:后面是两个//,所以D:就会被解析成为authority,具体可以比较上面的图,但是就文件来说,我们应该要把D:解析在path中间,因为就一个本地文件来说,其是不应该有host部分的。
正确的写法应该像下面这样,这样D:就不会被解析成authority了

file:/D:/tomcat/webapps

又或者是

file:///D:/tomcat/webapps
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值