org.apache.commons.io.FileUtils.readFileToString和文件路径中的空白

u12*_*123 4 java url

我试图在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);
}
Run Code Online (Sandbox Code Playgroud)

但它失败了:

java.io.FileNotFoundException: File 'C:\workspace\project\resources\test%20folder\test.txt' does not exist
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

String protocol = url.getProtocol();
  if(protocol.equals("file")) {
  File file = new File("C:\\workspace\\resources\\test folder\\test.txt");
  String str = FileUtils.readFileToString(file);
}
Run Code Online (Sandbox Code Playgroud)

我工作得很好.因此,当我手动键入带有空格/空白的路径时,它可以正常工作,但是当我从URL创建它时它不会.

我错过了什么?

Tom*_*icz 14

试试这个:

File file = new File(url.toURI())
Run Code Online (Sandbox Code Playgroud)

BTW,因为你已经在使用Apache Commons IO(对你有用!),为什么不在流而不是文件和路径上工作呢?

IOUtils.toString(url.openStream(), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

我正在使用IOUtils.toString(InputStream, String).请注意,我明确地传递了编码以避免操作系统依赖性.你也应该这样做:

String str = FileUtils.readFileToString(file, "UTF-8");
Run Code Online (Sandbox Code Playgroud)