0

I am trying to get to a file located under resources and get null:

 File propertiesFile = new File(this.getClass().getClassLoader().getResource(file).getFile());

file = Log.csv

Even if the file is directly under resource or under one of the folders under it. this.getClass().getClassLoader().getResource(file) - return null

RAGHHURAAMM
  • 1,099
  • 7
  • 15
Tamar
  • 13
  • 11
  • where you have kept your file ? – Derrick Oct 08 '18 at 06:34
  • Possible duplicate of https://stackoverflow.com/questions/44399422/read-file-from-resources-folder-in-spring-boot – Sudhir Ojha Oct 08 '18 at 06:36
  • make sure your file is present in src folder with correct name and format – Derrick Oct 08 '18 at 06:55
  • If my file located directly under resources folder this code working: File propertiesFile = new File(getClass().getClassLoader().getResource(file).getFile()); if my file located under folder inside resources, it will not work. why? – Tamar Oct 08 '18 at 07:24

2 Answers2

1
this.getClass().getClassLoader().getResource(file).getFile()

capture the path till resources folder, if you have folder inside resources then you have to give that along with the file name.

for example -

resources -> folder -> test.csv

Then give file name :

String file = "folder/test.csv";

Hope this helps!

Derrick
  • 3,669
  • 5
  • 35
  • 50
0

Resources are not real Files on the file system, but on the class path. They could be packed in a jar with an URL like "jar:file://.../xyz.jar!test.csv". Hence use an InputStream.

InputStream in = getClass().getResourceAsStream("/test.csv");
String userHome = System.getProperty("user.home");
Path path = Paths.get(userHome, "test2.csv");
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);

Resources should be considered read-only; hence use them as template, initial empty file, read-only data or such.

The ClassLoader has only absolute paths under the root src/main/resources, without starting /. The Class has URLs relative to the class' package directory (but under src/main/resources), or starting with / an absolute path.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138