0

My current application needs to get data from a file to initialize its attributes. It needs to be stored in a file to enable modification to the user.

String strFile = ClassLoader.getSystemResource("myFile.csv").getPath();
if(strFile==null)
        throw new Exception("File not find");
BufferedReader br = new BufferedReader(new FileReader(strFile));
//Begin reading file process..

My problem is that strFile is not null but I have a java.io.FileNotFoundException when br is initialized, see the following stack:

java.io.FileNotFoundException: C:\Users\TH951S\My%20Documents\Eclipse\Workspace
                                 \My%20App\bin\myFile.csv 
                                 (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)

I checked that the file is in the designated path and everything seems correct.

Does anyone knows why this is happening? Or is there another way to get a file when the path is unknown?

Thanks for reading and more for answering,

ArtiBucco
  • 2,199
  • 1
  • 20
  • 26

2 Answers2

3

I solve my issue, one of those that make you feel stupid for not solving it sooner.

URLs are encoding spaces with value %20 and Java do not replace the value by the space character when the FileReader is initialized. Therefore it is necessary to change %20 by " ".

There is also another way of counturning it. It is also possible to initialize the BufferedReader with an InputStreamReader as following:

InputStream in=ClassLoader.getSystemResourceAsStream("myFile.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
halfer
  • 19,824
  • 17
  • 99
  • 186
ArtiBucco
  • 2,199
  • 1
  • 20
  • 26
1

Just for completeness: I struggled with the same problem but the result had to be a File object (because I needed the size of the file).

URL url = ClassLoader.getSystemResource("myFile.csv");
File file = new File(url.toURI());
System.out.println("Correct path: " + file.getAbsolutePath());
System.out.println("Size of file: " + file.length());

The solution is inspired by sysLoader.getResource() problem in java.

I was surprised that I had to go over so many classes but I didn't find a closer solution.

Community
  • 1
  • 1
Daniel Alder
  • 5,031
  • 2
  • 45
  • 55