Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.apache.commons.io.FileUtils.readFileToString and blanks in filepath

Tags:

java

url

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?

like image 566
u123 Avatar asked Jan 09 '13 22:01

u123


People also ask

How do I install Apache Commons IO?

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.

What is Java FileUtils?

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.

What is FileUtils deleteQuietly?

FileUtils. deleteQuietly will suppress all exceptions. You can check the return value (true/false) if anything was deleted.


1 Answers

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");
like image 149
Tomasz Nurkiewicz Avatar answered Sep 29 '22 12:09

Tomasz Nurkiewicz