1

I work on a Java console application. There is a property in my application.properties file, which contains another file name as a value of a property, like

my.file.location=file:myDir/myFileName

In the code I try to get the file like this:

@Value("${my.file.location}")
private File myfileLocation;

If I start the application from the directory, which contains jar file, the file is resolved, but when I run my application from a different location, the file location is not valid.

I can't have this file on classpath, it must be external to the jar file.

How can I make the file path to be relative to my jar file and not to the current working directory?

Michal Krasny
  • 5,434
  • 7
  • 36
  • 64

1 Answers1

2

I believe this has nothing to do with Spring right? You just want to load configuration file, that is inside your application, unpacked, so the user can modify it, ok?

First, you may try to always setup the working directory, which I believe is more "standard" solution. In windows you can make a link, that specifies the Start in section and contains the path to your jar file (or bat or cmd, whatever).

If you insist on using the jar path, you could use How to get the path of a running JAR file solution. Note, that the jar must be loaded from filesystem:

URI path = MySpringBean.class.getProtectionDomain().getCodeSource().getLocation().toURI();
File myfileLocation = new File(new File(path).getParent(), "/myDir/jdbc.properties");
Community
  • 1
  • 1
vnov
  • 335
  • 1
  • 10
  • Thank you for provided answer. I was wondering, how to use the @Value("${my.file.location}") relative to the jar file, so this question is really related to Spring. – Michal Krasny Jan 11 '16 at 13:28
  • Well, you can call `myfileLocation.getPath()` to get the relative path, but than you still have to create new `File` with the full path. You could do this completely using spring [SpEL](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html), if you need it. – vnov Jan 11 '16 at 14:34