Java 中的文件、URI 和 URL 冲突
尝试在文件和 URL 之间进行转换时,特别是当文件/路径名称中包含空格时,我遇到了一些奇怪的行为。有什么安全的方法可以在两者之间进行转换吗?
我的程序具有文件保存功能,其中实际的“保存”操作被委托给需要 URL 作为参数的外部库。但是,我还希望用户能够选择要保存到哪个文件。问题是,当在文件和 URL(使用 URI)之间进行转换时,空格显示为“%20”并扰乱各种操作。考虑以下代码:
//...user has selected file
File userFile = myFileChooser.getSelectedFile();
URL userURL = userFile.toURI().toURL();
System.out.println(userFile.getPath());
System.out.println(userURL);
File myFile = new File(userURL.getFile());
System.out.println(myFile.equals(userFile);
这将返回 false(由于“%20”符号),并且会在我的程序中引起严重问题,因为文件和 URL 被移交,并且经常必须对它们执行操作(例如获取父目录/子目录) )。有没有办法让文件/URL 处理对于带有空格的路径是安全的?
PS 如果我的路径中没有空格(并且路径看起来相等),则一切正常,但这是我无法强加的用户限制。
I am getting some strange behavior when trying to convert between Files and URLs, particularly when a file/path has spaces in its name. Is there any safe way to convert between the two?
My program has a file saving functionality where the actual "Save" operation is delegated to an outside library that requires a URL as a parameter. However, I also want the user to be able to pick which file to save to. The issue is that when converting between File and URL (using URI), spaces show up as "%20" and mess up various operations. Consider the following code:
//...user has selected file
File userFile = myFileChooser.getSelectedFile();
URL userURL = userFile.toURI().toURL();
System.out.println(userFile.getPath());
System.out.println(userURL);
File myFile = new File(userURL.getFile());
System.out.println(myFile.equals(userFile);
This will return false (due to the "%20" symbols), and is causing significant issues in my program because Files and URLs are handed off and often operations have to be performed with them (like getting parent/subdirectories). Is there a way to make File/URL handling safe for paths with whitespace?
P.S. Everything works fine if my paths have no spaces in them (and the paths look equal), but that is a user restriction I cannot impose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您使用 URL 来构造第二个文件:
如果您坚持使用 URI,则效果会更好:
或
在测试带有空格的文件名时,两种方法都对我有效。
The problem is that you use URL to construct the second file:
If you stick to the URI, you are better off:
or
Both ways worked for me, when testing file names with blanks.
改为使用..
应该返回
true
。Use instead..
That should return
true
.