Creating a new folder in resources folder and read-write text files there (Maven Project)

时间:2015-07-08 15:43:35

标签: java maven intellij-idea

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?

1 个答案:

答案 0 :(得分: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: