Java中存在冲突的文件,URI和URL [英] Files, URIs, and URLs conflicting in Java
问题描述
尝试在文件和URL之间进行转换时,我遇到了一些奇怪的行为,特别是当文件/路径名称中包含空格时。有没有安全的方法在两者之间进行转换?
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?
我的程序有一个文件保存功能,其中实际的保存操作被委托给需要URL的外部库作为参数。但是,我还希望用户能够选择要保存的文件。问题是,当在File和URL之间进行转换时(使用URI),空格显示为%20并且搞乱了各种操作。请考虑以下代码:
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);
这将返回false(由于%20符号),并且在我的程序中导致严重问题,因为文件和URL被切换,并且通常必须使用它们执行操作(如获取父/子目录)。是否有如何使文本/ URL处理对于具有空格的路径安全?
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?
PS如果我的路径中没有空格(路径看起来相同),那么一切正常,但是是我不能强加的用户限制。
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.
推荐答案
问题是您使用URL构建第二个文件:
The problem is that you use URL to construct the second file:
File myFile = new File(userURL.getFile());
如果您坚持使用URI,那么您最好:
If you stick to the URI, you are better off:
URI userURI = userFile.toURI();
URL userURL = userURI.toURL();
...
File myFile = new File(userURI);
或
File myFile = new File( userURL.toURI() );
当用空格测试文件名时,这两种方式都适用于我。
Both ways worked for me, when testing file names with blanks.
这篇关于Java中存在冲突的文件,URI和URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!