构造URL对象时出现Java MalformedURL异常 [英] Java MalformedURL Exception when constructing a URL object

查看:993
本文介绍了构造URL对象时出现Java MalformedURL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于 Oracle文档试图构造一个URL并将其链接到我的HDD上的路径.我使用以下代码来做到这一点:

based on the Oracle documentation I tried to construct a URL and link it to a path on my HDD. I used the following codes to do so:

 String path = home+ File . separator + " dict ";
 URL url = new URL(" file ", null , path );

但是,尽管在Oracle文档中,据说file可以是第一个参数的协议之一,但实际上它给了我以下例外:

but then ,though on the Oracle documentation it is said that file can be one of the protocols at first argument, but it giving me the following exception in the practical:

Exception in thread "main" java.net.MalformedURLException: unknown protocol:  file 

为什么会这样?

推荐答案

请勿为此使用URL.并且不要使用File .这是2014年,我们有java.nio.file.

Don't use URL for that. And don't use File. This is 2014, we have java.nio.file.

改为使用它,它将立即给出正确的结果:

Use this instead, it will give an immediate, correct result:

final URL url = Paths.get(home, "dict").toUri().toURL();

默认文件系统始终为 file.

此外,为什么要使用URL,而不要使用URI?请注意,您的代码在Windows上将无法使用(URI的路径部分中不能包含反斜杠).

Also, why a URL and not a URI? And note that your code wouldn't work on Windows (you can't have a backslash in the path component of a URI).

edit:您使用的手册似乎也出现了很多错误;首先,它假设使用Unix系统!

edit: it also appears that the manual you use gets many things wrong; for one, it assumes a Unix system!

您遇到的一个问题是您的系统上未设置WNHOME环境变量.结果,您得到的路径是您的当前目录,再加上null"dict".

And one problem you have is that the WNHOME environment variable is not set on your system; as a result, you get a path which is your current directory, plus null, plus "dict".

将代码更改为此:

final String wnhome = System.getenv("WNHOME");
if (wnhome == null)
    throw new IllegalStateException("WNHOME environment variable is not set");
final URL url = Paths.get(wnhome, dict).toUri().toURL();

通常,您会看到一个异常...由您自己决定在此处设置WNHOME环境变量.

Normally you will see an exception... It is up to you to set the WNHOME environment variable here.

这篇关于构造URL对象时出现Java MalformedURL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆