1

I referred to this link to get an idea about how to access files in resource directory.

My java file is at /home/cloudera/Documents/upport/src/main/java/org/mainProject/index/services/SetupService.java and the resources directory is at /home/cloudera/Documents/Support/src/main/resources. I wish to create a folder config in resources and write two text files to it.

Copying to any folder using Files.copy() gives me Access Denied. mkdir() and createDirectory() were also giving permission errors. So I thought I'll manually copy-paste the files and then access them.

For accessing the files in resources/config I tried the following but:

This gives me wrong path:

File file = new File("resources/config/file.txt");
String absolutePath = file.getAbsolutePath();

This gives me null:

SetupService.class.getResource("config/file.txt"));

How should I go about it?

Community
  • 1
  • 1
Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130
  • Hint: Keep in mind, that a test case within eclipse, a mvn clean install and your runtime will have different behaviors,... one approach may work for junit, but not during runtime,... – slowy Jul 08 '15 at 15:52

1 Answers1

0

Resources below src/main/resources/ end up in the JAR file which Maven creates - Java wants it that way. They aren't visible anymore as files when you run the JAR. That's why you can't create a path to them.

To access the resources, you need to ask the ClassLoader for a URL (.getResource("...relative/path...")) or an InputStream (getResourceAsStream()).

If you want to save config options, you should use the Preferences API or maybe create a Properties file in the home folder of the user or in a folder defined by a system property.

Related:

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820