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:workspaceprojectresourcestest%20foldertest.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?
Advertisement
Answer
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");