[英]org.apache.commons.io.FileUtils.readFileToString and blanks in filepath
I am trying to read a file to string using org.apache.commons.io version 2.4 on windows 7.我正在尝试在 Windows 7 上使用 org.apache.commons.io 2.4 版将文件读取为字符串。
String protocol = url.getProtocol();
if(protocol.equals("file")) {
File file = new File(url.getPath());
String str = FileUtils.readFileToString(file);
}
but it fails with:但它失败了:
java.io.FileNotFoundException: File 'C:\workspace\project\resources\test%20folder\test.txt' does not exist
but if I do:但如果我这样做:
String protocol = url.getProtocol();
if(protocol.equals("file")) {
File file = new File("C:\\workspace\\resources\\test folder\\test.txt");
String str = FileUtils.readFileToString(file);
}
I works fine.我工作正常。 So when I manually type the path with a space/blank it works but when I create it from an url it does not.因此,当我手动输入带有空格/空白的路径时,它可以工作,但是当我从 url 创建它时,它却没有。
What am I missing?我错过了什么?
Try this:试试这个:
File file = new File(url.toURI())
BTW since you are already using Apache Commons IO (good for you!), why not work on streams instead of files and paths?顺便说一句,既然您已经在使用 Apache Commons IO(对您有好处!),为什么不处理流而不是文件和路径呢?
IOUtils.toString(url.openStream(), "UTF-8");
I'm using IOUtils.toString(InputStream, String)
.我正在使用IOUtils.toString(InputStream, String)
。 Notice that I pass encoding explicitly to avoid operating system dependencies.请注意,我显式传递编码以避免操作系统依赖性。 You should do that as well:你也应该这样做:
String str = FileUtils.readFileToString(file, "UTF-8");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.