Java File.toURL() 已弃用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/777423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File.toURL() deprecated?
提问by Lucky
Why is the function java.io.File.toURL()
deprecated? I need to pass an URL to Toolkit.createImage()
which accepts a URL object. Javadoc recommends me to use File.toURI().toURL()
. However:
为什么java.io.File.toURL()
不推荐使用该功能?我需要传递一个Toolkit.createImage()
接受 URL 对象的 URL。Javadoc 建议我使用File.toURI().toURL()
. 然而:
C:\Documents and settings\Administrator\...
C:\Documents and settings\Administrator\...
becomes:
变成:
C:\Documents%20and%20settings\Administrator\...
C:\Documents%20and%20settings\Administrator\...
which obviously is an invalid file location. I've found File.toURL() to create URL's without the escaping, however it's deprecated. Although it works I'm scared of using deprecated functions. What's a method that's not deprecated that does the same thing?
这显然是一个无效的文件位置。我发现 File.toURL() 可以在没有转义的情况下创建 URL,但它已被弃用。虽然它有效,但我害怕使用不推荐使用的函数。什么是不被弃用的做同样事情的方法?
EDIT: Right now my code looks like:
编辑:现在我的代码看起来像:
spriteImage1 = tkit.createImage(new File("./images/sprite1.png").getCanonicalFile().toURL());
EDIT: I need to create an Image from a folder outside my .jar file. I'll need a relative location ("./images/sprite1.png"). The method createImage(String) throws an exception when I try to give it the relative path.
编辑:我需要从我的 .jar 文件之外的文件夹创建一个图像。我需要一个相对位置(“./images/sprite1.png”)。当我尝试为其提供相对路径时,方法 createImage(String) 会引发异常。
回答by Powerlord
Wouldn't it be easier to use Toolkit.createImage(File.getPath());
instead?
使用它不是更容易Toolkit.createImage(File.getPath());
吗?
回答by Pesto
Why don't you just use the createImage
function that takes a Stringfilename instead?
为什么不直接使用接受字符串文件名的createImage
函数呢?
回答by ks.
Use: URL url2 = file.toURI().toURL();
使用: URL url2 = file.toURI().toURL();
回答by i'm not an expert..
i think that you must write the url in this way
我认为您必须以这种方式编写网址
C:/Documents and settings/Administrator/...
C:/文件和设置/管理员/...
not in this
不在这个
C:\Documents and settings\Administrator...
C:\文档和设置\管理员...
回答by Francisco Valle
I think the right answer to this question is the one exposed in this link http://www.jguru.com/faq/view.jsp?EID=1280051
我认为这个问题的正确答案是这个链接中公开的答案http://www.jguru.com/faq/view.jsp?EID=1280051
As exposed in the link above, the right way to do this is:
如上面的链接所示,正确的方法是:
// Supposing f is the referenced file in code and we want to
// get an URL instance without deprecation warnings.
URL externalForm = f.toURI().toURL();
There is no catch for MalformedURLException as the question is about deprecation of the method file.toURL().
MalformedURLException 没有捕获,因为问题是关于方法 file.toURL() 的弃用。
Hopes this helps.
希望这会有所帮助。