0

I´m reading a file from my resource folder in a unit test

I can see the file in the target/test-classes

But when I try to wrap the file into a fileInputStream this one throw the exception because cannot find the file

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("CV.pdf").getFile());
FileInputStream fis = new FileInputStream(file)

Output debuging:

classLoader.getResource("CV.pdf"):

file:/Users/Development/File%20-%20Test%20Java%20trial/Code/target/test-classes/CV.pdf

Maybe it could be because my folder has whitespace names?

The file is there for sure, I can seen it in that folder.

What I´m doing wrong here?.

Regards.

paul
  • 12,873
  • 23
  • 91
  • 153
  • Well what is the value in the URL that `getResource(...)` is returning? What values does the `getFile` call return? What is the file path that ends up in `file`? – greg-449 Nov 06 '16 at 11:03
  • I update my question with the output – paul Nov 06 '16 at 11:14
  • 1
    The path is URL encoded, you need to decode it http://stackoverflow.com/q/6138127/2670892 – greg-449 Nov 06 '16 at 11:22
  • 1
    **Do not** decode that URL. It is correct the way it is! The problem is that the URL.getFile() method **does not** convert a URL to a file name, it just returns a URL’s path portion. You should not be trying to convert the URL to a file at all, since you won’t be able to run from a .jar if you do that. – VGR Nov 06 '16 at 17:35

1 Answers1

2

Do you really need FileInputStream?

Actual file can be even inside jar (if you instruct maven to make test-jar).

More flexible way is to use InputStream instead:

try(final InputStream is = getClass().getResource("CV.pdf").openStream()) 
{
    //Do something with is
}
rkosegi
  • 14,165
  • 5
  • 50
  • 83