Java JAR file runs on local machine but missing file on others - java

The JAR file consists of the ffmpeg.exe file and it can run normally on my machine without any problems. However, if I try to run it on another computer it would tell me that java.io.IOException: Cannot run program "ffmpeg.exe": CreateProcess error=2,The system cannot find the file specified from the stacktrace. The way I imported it was
FFMpeg ffmpeg = new FFMpeg("ffmpeg.exe"); //in res folder
...
//ffmpeg class
public FFMPEG(String ffmepgEXE) {
this.ffmepgEXE = ffmepgEXE;
}

The quick fix is you have to put ffmpeg.exe in the same folder with your .jar file.
If you want to read file from resources folder, you have to change this code:
URL resource = Test.class.getResource("ffmpeg.exe");
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();
FFMpeg ffmpeg = new FFMpeg(filepath);

Related

URI is not hierarchical. How to get File Path using getResourceAsStream

private void generateDATFiles() throws Exception {
File shellScriptPath= new File((this.getClass().getResource("/Vorlagen/Simulation/test.sh").toURI()));
ProcessBuilder pb = new ProcessBuilder(shellScriptPath.getAbsolutePath());
Process p = pb.start();
}
So I have a shell script which I want to execute. The problem is that I need the file path and I can get it using getResource but I get the error that my uri is not hierarchical so I found out that I need to use getResourceAsStream to avoid the error, but my question is how I can get the file path using getResourceAsStream?
Unfortunately it won't be an easy thing to do. If you pack the .sh script together with the other part of the program in a single .jar it won't work. You can only access it as a resourcestream and not as an URI (even if in development mode you can get the actual URI). That's because the .sh AND the class files and everything is actually in the same file for the file system (.jar).
It's not so much a java limitation as the OS. If the .sh is bundled in the jar/war/any other archive you cannot run it from the java code. (Actually you cannot do it from the command prompt either).
In order to solve it you can get the input stream and write the contents in a temporary file (you can use the java createTempFile functionality) and then execute that one. Or you can extract the .sh file from the jar(zip) and execute it
Try to do with this way.
class J{
public static void main (String a[]){
{
System.out.println(J.class.getResourceAsStream("/file.txt")
}
}

NetBeans Java Project from command line: Working directory is System32

If I run my Java program in NetBeans and follow the information given in the output window to run from a command line:
To run this application from the command line without Ant, try:
java -jar "C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\assignment2.jar"
The program starts to run, but when it comes to run the following code to open a .txt file (my "database"):
System.out.println("Loading database of stored transactions...");
try
{
file = new File("TransactionDetails.txt");
inFile = new Scanner(file);
}
// if the log couldn't be found in the default program location
catch (FileNotFoundException ex)
{
System.out.println(CustomMessages.FileNotFound() +
System.getProperty("user.dir")); // display default directory
System.out.println(CustomMessages.systemExit());
System.exit(1); // the program needs the log to function as intended
}
It cannot find the .txt file and prints the default directory as the Windows System32 folder. How can I specify the location to be the Project folder as expected?
You could use an absolute path to the file instead of a relative path. e.g
file = new File("C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\TransactionDetails.txt");
inFile = new Scanner(file);
You cannot rely on the current working directory to be set to anything.
Either provide the file as a class path resource instead or ask the jvm where the class is located in the file system and locate the file relative to that.
For a read only file I would consider providing it as a resource.

Error while trying to read a file

In my Java/Maven application, I'm trying to read some files that is in resources folder. I just can read this files when execute the application in Eclipse, but when I try to run the application with the command bellow I get a Nullpointer because the file is not found.
java -Dserver.port=$PORT -Dspring.profiles.active=dev -jar my-war.war
I'm reading the file with this command:
String string = new String(
Files.readAllBytes(
Paths.get(ClassLoader.getSystemResource("fileFolder/file.html").toURI())));
the problem was solved changing the way that I read the resource:
IOUtils.toString((new ClassPathResource("fileFolder/file.html").getInputStream()));
because the resources when in .war not are treated as files, so read them as file will throw an exception

Hot to set the working directory of a process in Java

I am trying to set the working directory of a process that will be running an exe.
Here is what I have so far:
public Process launchClient() throws IOException {
File pathToExecutable = new File(currentAccount.getAbsoluteFile()+"/Release", "TuringBot.exe");
System.out.println(pathToExecutable);
ProcessBuilder builder = new ProcessBuilder(pathToExecutable.getAbsolutePath());
builder.directory( new File( currentAccount, "Release" )); // this is where you set the root folder for the executable to run with
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
return builder.start();
}
but every time I launch it, the exe attempts to run but fails to because the current directory is wrong and it can't properly access the required files.
EDIT:
Here's a little more about whats going on...
I have x amount of client folders, each contains an executable file that needs to be started and relies on the contents of its local folder to execute properly, however when running this code to launch each executable file the working path for each unique executable is not being applied and is rather the default directory (the JAR's locations).

exec, files location problem

In my jar application I do some calculations in exe program. When files and program.exe was in the same dir I used this command:
String[] str={"program.exe", "file1.txt", "file2.txt"};
pr = rt.exec(str);
and it worked great. But when I moved files to other dir and I try use this command:
String[] str={"program.exe", "temp\\file1.txt", "temp\\file2.txt"};
pr = rt.exec(str);
program.exe doesn't see files. What is more odd it start to see files when I change its names for anything else that default. file1.txt, file2.txt and temp are created in my jar program before program.exe start.
edit:
When problem started I try sth like this: default names file1.txt and file2.txt, I changed to aaa.txt and bbb.txt (in windows), and then:
String[] str={"program.exe", "temp\\aaa.txt", "temp\\bbb.txt"};
and it works.
edit2:
Now I know that problem is in program.exe. When I use it from command line (not from jar), like this:
program.exe temp\file1.txt temp\file2.txt
error:
FANN Error 1: Unable to open configuration file "temp\file1.txtÉ║#" for reading.
fann is artificial neural network library. When I copy files to program.exe dir:
program.exe file1.txt file2.txt
it works! When I changed files names in temp and do:
program.exe temp\file1aaa.txt temp\file2bbb.txt
it works also! So it is fann lib bug?
I'd use the ProcessBuilder api (it gives you much more control than Runtime.exec()) and I'd also use absolute paths:
File directory = new File("/path/tp/program.exe's/parent");
int returnCode = new ProcessBuilder("program.exe",
new File(directory, "temp/file1.txt").getAbsolutePath(),
new File(directory, "temp/file2.txt").getAbsolutePath()
)
.directory(directory).start().waitFor();
Give complete path of the filename and see. Something like below
String[] str = {"program.exe", "D:\\temp\\file1.txt", "D:\\temp\\file2.txt"};
If your OS is UNIX based then change it accordingly.
Have you tried relative path for finding the location
like
abc (folder)
-> code(folder)
-->Program.Java
-> temp
--> file1.txt
so
when u run ur program in Eclipse IDE
ur relative path will be from program.java file is
../temp/file1.txt
And try to use / instead of \ so that it wont take as an escape character.
when u run from a jar
You need to extract the temp folder from jar to outside
abc (folder)
-> jar (folder)
-->Program.jar
-> temp
--> file1.txt
OR
Read the jar content from the program as a zip file. Reach your temp folder inside it by code and then read the content as input stream.

Categories