Org.apache.commons.io.FileUtils.readFileToString and spaces in the file path

I am trying to read a file in a line 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 fail:

 java.io.FileNotFoundException: File 'C:\workspace\project\resources\test%20folder\test.txt' does not exist 

but if I do this:

 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 work great. Therefore, when I manually type the path with a space / space, it works, but when I create it from the URL, it is not.

What am I missing?

+4
source share
1 answer

Try the following:

 File file = new File(url.toURI()) 

By the way, since you are already using Apache Commons IO (good for you!), Why not work with streams instead of files and paths?

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

I am using IOUtils.toString(InputStream, String) . Please note that I skip encoding explicitly to avoid operating system dependencies. You should also do this:

 String str = FileUtils.readFileToString(file, "UTF-8"); 
+13
source

All Articles