1

I need to reference a file in the classpath purely via the string value.

This is the code which can't be changed:

CSVReader reader = new CSVReader(new FileReader(fileName),
            CSVParser.DEFAULT_SEPARATOR,
            CSVParser.DEFAULT_QUOTE_CHARACTER,
            CSVParser.DEFAULT_ESCAPE_CHARACTER, 1)

new FileReader(fileName) calls new FileInputStream(fileName) which in turn calls this(name != null ? new File(name) : null). As the name is not null, this boils down to new File(name). The issue with this is, that the file I need to reference is a classpath resource(src/main/resources/filters/filterfile.csv).

I tried a few ways to reference this file purely by path, like

  • src/main/resources/filters/filterfile.csv

  • /filters/filterfile.csv

  • classpath:/filters/filterfile.csv

but none worked, as I always get a java.io.FileNotFoundException (which is understandable).

So the question is, is it possible to reference a file in the classpath purely by the string? And if so, how can this be done?


As it might help:

The application is a web app which will run on a tomcat 9 server. So it would kind of be possible to hardcode the path. The issue that this causes is running the application in eclipse then, as the paths wont match at all.

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
  • The *easiest and most compatible* way to do this is probably to read the resource from the classpath and store it in a temporary file and pass the name of *that* temporary file to the method. One of the issues is that resources on the class path may or may not be represented by files on a local disk (they might be in a jar file or loaded from a remote URL, in both of those cases they wouldn't exist as files on the disk). – Joachim Sauer Nov 21 '19 at 15:42
  • @JoachimSauer I have added some more info which might help. Regarding your suggestion with the temporary file. As the paths are set during initilization, I see no way to hook into it. I would need to manually initialize that part of the application. And if I go that way, then I can also directly set the right filename via `getClass().getResource("/filters/filterfile.csv").getFile()`. While this could work, it would be far more convenient to have spring simply autowire all the stuff and resolve the filenames with some magic. Though I am open to suggestions (yours already helped) – XtremeBaumer Nov 21 '19 at 15:54

0 Answers0