File relative to jar using Spring - java

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?

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");

Related

Java can't get relative path for file

Image DescriptionTrying to access a test.txt file that is in the same location as my HelloController.java file but for some reason, it is showing that the file does not exist. I've tried moving the file around but it does not work.
Using the absolute path works, but this is a shared project so it will be ran on other computers. Any suggestions would be much appreciated.
Your best bet is to add it to the class path and reading it as a class path resource.
The relative path root is your "working directory". Which means if you try to access "." you will start at your working directory. This directory is only set once for your application and is normally the folder which was opened when you started it.
When working with IDEs (like in your case) the working directory will be the root folder of your project (So the folder in which the pom.xml and src folders are located.
If you want to access the file via the normal file API you are currently using, just put the file in that diretory and it should work (given you share it with the other people in the same location).
If you need the file to be inside your generated output jar-file, you will need to use the File as a resource (See duffymo's answer), as the file does not exist by itself on the file system, but as a file inside your jar-file.
If you want to know your current working directory, you can create a File refrence to "." and expand it to an absolute path (Which will replace refrences like "." and ".." and generate a file path from your root) and then write it to the console. This would look something like this:
// Get refrence to the current working directory
File workingDirectoryReference = new File(".");
// Convert it to an absolute path string
String absolutePath = workingDirectoryReference.getAbsolutePath();
// Output to console
System.out.println(absolutePath );

How to load property file located inside jar file

How to load property files placed in resource folder of an executable jar file. Here my app itself is a jar and it executes on it own. It need to find this property file (placed within itself under resource folder) at runtime depending on the path mentioned in the code. I have used below two methods but it didn't help me. Point here is, both these options are working fine when i execute in eclipse, but doesn't work when I pack it into an executable jar. It throws NullPointerException. Only problem I see here is that jar is not able to pick the property files with given path. Any help would be appreciated.
Method 1: Using Apache Commons Configuration
URL propFileURL = XYZ.class.getClassLoader().getResource("/config.properties");
Configuration propertyConfiguration = null;
propertyConfiguration = new PropertiesConfiguration(propFileURL);
In above case I'm getting ConfigurationException. Class is not able to find file mentioned in given path.
Method 2: Using getResourceAsStream. I know that getResource doesn't work if we are to load files from network on in any other location.
InputStream is =XYZ.class.getClassLoader().getResourceAsStream("/config.properties");
Properties prop = new Properties();
prop.load(is);
In this case, I'm getting nullPointerException.
Let me know if you need more details.
jar content Heirarchy
Properties file - /java-file-io-application/src/main/resources/config.properties
XYZ class - /java-file-io-application/src/main/java/org/bc/xyz/iplugin/utilities/XYZ.java
Looks like you might be building your jar incorrectly. Files from 'src/main/resources' would be expected at the root of the jar file. If your jar file contains the 'src/main/resources' directory, something's off with your build.

finding static file in jar

I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored a csv file in a folder. To use relative paths in the code in the jar I access it using
MyClass.class.getResource(ApplicationConstants.ALIASESFILE).getPath();
and this works fine when I deploy (glassfish) and use the project as a separate application. But when I am using the same from within another project, it gives a path as shown below
D:\javaProjects\AutomodeGS_Prachi\lib\internal\RESTWSGS.jar!\aliases\aliases.csv
I am getting a file notfound exception.What could be wrong?
The getResource() method is returning a "jar:" URL. The path component of that URL is not a normal filesystem pathname, and can't be opened directly using Java's file classes.
The simple way to do this is to use Class.getResourceAsStream(...) to open the stream. If you need an "identifier" for the JAR entry, use Class.getResource(...), but then open the stream using URL.openStream().
This works fine from glassfish may be because glassfish has exploded jar on file system so that your csv file is acutually a file to the file system,
if you try to read it from another project it fails because the jar containing your file is in classpath that is fine, but the csv file is under jar file and it is no longer a File
You can read it as Stream
InputStream is = MyClass.class.getResourceAsStream(ApplicationConstants.ALIASESFILE);

Access a file from a JAR in the same folder

I need to acces (create and read) a file from a JAR file (executable jar),
and that file should be created in the same directory as the JAR
I tried
this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work..
I also tried write just
File f = new File("myFile");
f.createNewFile();
and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)
This will give you the full path to the Jar:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:
String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();
(where the class name is Me).

Java JAR: Writing to a file

Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?
You shouldn't have to treat it as a classpath resource to write to a file. You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you?
You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). In eclipse, configure the working directory from within the run configuration dialog.
You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.
To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files:
// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);
And, from now on, you can create all your File's like this:
File myFile = new File(root, "config.xml");
Of course, root has to be in your scope.
Such resources (when altered) are best stored in a sub-directory of user.home. It is a reproducible path that the user should have write access to. You might use the package name of the main class as a basis for the sub-directory. E.G.
our.com.Main -> ${user.home}/our/com/

Categories