简体   繁体   中英

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.

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.

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?

IOUtils.toString(url.openStream(), "UTF-8");

I'm using 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM