Friday, 31 July 2015

Reading in a file when directory names have spaces in them

PROBLEM:

We were running some errors in our Jenkins build of some code, even though the code works on our computers. 

java.io.FileNotFoundException: File '/var/lib/jenkins/workspace/Email%20Project%20Release/target/test-classes/com/company/mailFolder/sample_email.txt' does not exist

I ssh'd to the Jenkins box and tried to ls on the directory name:

and I got

ls: cannot access 
/var/lib/jenkins/workspace/Email%20Project%20Release/target/test-classes/com/company/mailFolder/sample_email.txt: No such file or directory

Then I realised it was the '%20' -- it was trying to load a url encoded directory name..

Doing an ls this directory worked:

ls -l "/var/lib/jenkins/workspace/Email Project Release/target/test-classes/com/company/mailFolder/sample_email.txt'

I looked in the code and it was doing this:

File mailFolder = new File(getClass().getResource("mailFolder"));
File mailFile = new File(mailFolder, "sample_email.txt");

I tested doing the first line with a folder that had spaces in it and I found it would return a path with any spaces replaced by '%20'


SOLUTION:

From stackoverflow, I found that the best way to get the correct folder reference was to do this

File mailFolder = FileUtils.toFile(getClass().getResource("mailFolder"));
File mailFile = new File(mailFolder, "sample_email.txt");

At first, I tried to load the file directly and it only returned null. Getting the File reference to the folder first, then creating the reference to the file is the only way that works, despite what the Stackoverflow article said (REF).



REF:


No comments: