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?
Download Common IO ArchiveDownload the latest version of Apache Common IO jar file from commons-io-2.11. 0-bin. zip. At the time of writing this tutorial, we have downloaded commons-io-2.11.
Features of FileUtilsMethods to make a directory including parent directories. Methods to copy files and directories. Methods to delete files and directories. Methods to convert to and from a URL. Methods to list files and directories by filter and extension.
FileUtils. deleteQuietly will suppress all exceptions. You can check the return value (true/false) if anything was deleted.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With