4

I have a file users.txt with a file path of myPlugin/impl/src/main/resources/myPlugin/impl/src/main/java/com/company/myPlugin/impl/users.txt. I am trying to access this file from a Java class with a file path of myPlugin/impl/src/main/java/com/company/myPlugin/impl/UserManager. I don't want to hardcode a path because the working directory will change. I did try:

String path = System.getProperty("user.dir") + .....path to users.txt;

The problem with this is that it only works when I run the plugin locally. When it is deployed on another machine or server, the working directory won't contain all the files. What I really need is a way to open the file using only a relative path from myPlugin. I also tried

URL path = getClass.getResource("");

And then added the rest of the path but this did not work either. Is it even possible to use only a relative path that is not dependent on the current working directory? When I run my plugin on the server, the working directory does not contain the source code or directory structure.

SVN600
  • 345
  • 1
  • 5
  • 19

1 Answers1

1

The file location consists of two parts: myPlugin/impl/src/main/resources/ and users.txt. The first one is the location where the build system (Maven) finds your resources. The second is your actual resource.

Everything under myPlugin/impl/src/main/resources (both files and directories) will be copied to your classpath.

To answer your question, your file should be accessible via

getClass().getClassLoader().getResource("users.txt");
  • A small observation: this is assuming the file's location on the classpath is in the same package as wherever getClass().getResource() is invoked from. Which is not the case if I see the question. `getClass().getClassLoader().getResource()` may be the better advice. – Gimby Jul 22 '16 at 14:52
  • This, which in theory seems like it would work, does not. The path it generates is the correct path from the "/target/class" directory, but the file can't be found by the program. – SVN600 Jul 22 '16 at 15:08
  • @Gimby Given that the resource is in the default package, your correction is essential. Thank you. –  Jul 22 '16 at 15:11
  • Oh hold on - what is that `impl` directory? You'd normally have `myPlugin/src/main/resources` May be you need `myPlugin/src/main/resources/impl/users.txt` ? –  Jul 22 '16 at 15:13
  • I think (untested) that `getClass.getResource("/users.txt")` could also work (search from root of classpath). – Serge Ballesta Jul 22 '16 at 15:14
  • I added more of a directory structure to the path of the resources; following the usual syntax the company uses. The getClass.getClassLoader().getResource() method returns null and when I add a "/" to the resource name to be found, it also causes null issues. However, without the backslash it does get the correct path from the class directory created by the maven build – SVN600 Jul 22 '16 at 16:37
  • getClass.getResource() worked! – SVN600 Jul 22 '16 at 17:23