How to iterate on a folder located outside a .jar file running - java

I have a problem with my java app architecture. I want to deliver a simple .jar file generated with Spring Boot. I need to iterate over files presents in another folder, after running the .jar.
Here is the hierarchy of my directory:
enter image description here
I launch my .jar with a .bat or sh, with java -jar myApp.jar
I have to iterate on all files that are present in myApp/files
it seems simple but I can't find a way to do this ! I try a lot of things found here but nothing works !
I try this but had a nullPointer...
File jarFile = new File(myMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
String jarLocation = jarFile.getPath();
Could you help me please with some try to do !
Thanks !

Edit your .bat file to start into your myApp folder like this
#echo off
#do stuff
cd %myApp_folder%
java -jar myapp.jar
and you can resolve your folders via relative path like this:
File confFolder = new File("conf");
File filesFolder = new File("files");

Related

execute a .jar file from C# but it generates files at wrong location

I have coded a Minecraft Server Runner in C# WinForms which lets you run a Minecraft Server, a .jar file which needs to generate files. The problem is that I launch this .jar file via the .exe application, and the files generate at the .exe application location.
-- What I have tried:
I tried moving the .exe application to the specific server file location, but the application needs a restart to register this change which I don't want to happen.
I also don't want the user being forced to put the .exe application to the Server folder and restart it. Here is the code I use to launch the .jar file:
Process.Start("C:\user\documents\server\server.jar");
How can I fix this issue?
The jar file can be executed by the java -jar filename.jar. So use the following Process.Start call to invoke the jar.
Process.Start("java", "-jar C:\user\documents\server\server.jar", username, password, domain);
Hope this helps.
P.S: For this to work, either add the Java to your path or invoke with the java.exe's Path.
To fix this I executed the .jar file in the C# application via the CMD.
Here is the code I used instead:
string path = #"C:\user\documents\server\"; //Path to your server.jar file.
var process = new System.Diagnostics.Process();
process.StartInfo.FileName = path + "server.jar"; //Name of the .jar file.
process.StartInfo.WorkingDirectory = path;
process.StartInfo.UseShellExecute = true;
process.Start();
All credits go to "Olivier Rogier" ( https://stackoverflow.com/users/12031933/olivier-rogier ) for helping me find this solution

How to access outside file from java jar

I have a jar that is reading a file using below code:
Thread.currentThread().getContextClassLoader().getResource(fileName);
I want to run this jar using java -jar .jar command but I want to keep this file outside my jar, so that I can edit the jar file later on without touching the jar. Can anyone help me, how to run this jar so that it will pick up the file from outside.
There are multiple approaches you can do that and it will depend on where would you like to place this external file. For the sake of this answer, I will refer to this file as config file
Not In The Same Directory
The first approach is where you will need to place this file outside the JAR and not necessarily next to the JAR file in the same directory. In that case, you can pass the file location of the config file using either an environment variable (if you are running the JAR in a shell for example) or a Java property.
To use an environment variable, assuming you are using some Linux distro, then you can use the export command to set the value; something like this:
$ export CONFIG_FILE_LOC=/etc/myapp/config.file
You can then read the value in your code using the System class by using the following code:
String fileLocationEnv = System.getenv("CONFIG_FILE_LOC");
Alternatively, you can set this as a property by adding the following segment to your launch command:
$ java -Dconfig.file.location=/etc/myapp/config.file -jar myapp.jar
You can then read the value in your code using the System class for properties using the following code:
String fileLocationProp = System.getProperty("config.file.location");
In The Same Directory
If you need the config file to co-exist in the same directory as your JAR file, then you can use the following code to get the JAR directory and then append the filename to it. Here's the code (assuming a class named MyApp)
try{
new File(MyApp.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch(URISyntaxException exception){
System.out.println("Exception");
}
Hope that helps.
To open the file as a resoure, add the folder containing the file(s) you want to use, to your classpath:
java -classpath .;config -jar myjar.jar
This example adds the current directory and the config directory to your classpath.
Multiple folders can be specified by using a separator. On windows use ';' , on unix use ':' .
To open the file as a File, you can just use
new File("configfile")
which will look in the working directory (directory where you launched your java)

Error with .jar file -- attempts to locate file in jar folder

Hopefully this will make some sense. I'm new to Java and while I've built .jar artifacts before, I have never had to build a program that takes another file as input. I'm running into a weird problem and I'm not sure how to fix it.
Basically, I have a Main.java class that calls a .txt file and passes it to another class, myClass.java. I generated a .jar file with IntelliJ, which inserted itself inside its own folder.
To make things easier, here is the basic structure of my program.
/src
/com.myProgram
Main.java
input.txt
MyClass.java
/out
/artifacts
/myProgram_jar
myProgram.jar
And here is a basic version of what's in Main.java
myClass mc = new myClass("input.txt");
I tried running the .jar file with the command "java -jar myProgram.jar", and I get the error "The system cannot find the path specified". I ran getCanonicalPath() on input.txt. Apparently my program is looking for input.txt in out/artifacts/myProgram_jar instead of in the src/ folder.
What can I do? Even when I put the full path to force the program to look in the src/ folder, it will still attempt to look in the myProgram_jar folder and throw an error. So I cannot execute the file at all. Any suggestions for solving this error are greatly appreciated!
When you build to jar file, it's not a File anymore. A File is only a physical file on the file ystem.
So have 2 way to fix it:
1. You export the txt file to system as D:/New folder, then you get this file with path of this file.
2. You can try this:
try {
URL url = new URL(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().toString()+your path to file in structre);
InputStream in = url.openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(PrepareGUI.class.getName()).log(Level.SEVERE, null, ex);
}

How to get the absolute path of the executed jar?

How do I get the location of the executed jar? I found a lot of solutions but none of them work for me. When I run them in my IDE everything is fine. As soon as I build a jar file and run it with java -jar myapp.jar the output is like /.../myapp.jar!/foo/bar
I will run the code in myapp.jar - not in any library.
Location of jar: /home/me/dev/myapp/myapp.jar
Expected output: /home/me/dev/myapp/
I don't want the working directory as I would get with System.getProperty("user.dir");
Why I want to do this:
I want to store and load a file beside the actual jar. Like
/home/me/bin/myapp/myapp.jar
/home/me/bin/myapp/license.key
I want to avoid storing the file into some generic folder like System.getProperty("user.home");. And I don't want to store the file within the jar file.
java.nio.file.Paths.get(".").toAbsolutePath() will return absolute path to current directory.
I use something along these lines:
[YourClass].class.getProtectionDomain().getCodeSource().getLocation().getPath()
Regards

How can I find a file while in my java code

I am stuck on a how to robustly find a file path from my Java program. If I am using Linux, I can launch my program from my home folder, and then I can't say find my file at ./myProgram/myFile. Is there a good way to find my file no matter what directory my console is in?
If you are trying to access the file using the path:
./myProgram/myFile
in your program, but you aren't executing the program from the myProgram directory, then you're Java code won't see the file. Try providing it with the full path instead of the relative path. If myProgram is a directory found in your user's Documents directory then a full path would likely look something like this:
/home/*username*/Documents/myProgram/myFile
You could also build in functionality that lets you select the file by navigating through the directories and listing the files. The would provide the user with options to choose which file to utilize in the program.
You can just as well cd to the myProgram directory before executing the file and then the relative path ./myProgram/myFile should work.
Hope that helps.
Try this:
File f = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "myFile.txt");

Categories

Resources