Execute batch file from Java code - java

I tried to run the batch file from java code, bat file is running but in bat file internally it is calling proxyServer.js file.This .js file is not running.
Below is the sample code.
try {
String path="cmd /c start C:\\AxoneES_Viewers_Integration-2016Q3-SNAPSHOT_201609021003\\AxoneViewers.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);
} catch(IOException ex) {
System.out.println("Exception Found");
}
As i mentioned internally it is calling .js file where they declared path of the .js file, below is the code , which declared the path.
cd viewers\apps\maxq\
node proxyServer.js
while running the bat file it is not able to find the path of .js file and it not running.
Can you help me is there any approach to execute the bat file from java.

Try editing the batch file to use absolute file names instead of relative file names. You mentioned your batch file has the lines
cd viewers\apps\maxq\
node proxyServer.js
Change the first line to something like C:\full\path\to\viewers\apps\maxq\. Check out this answer for the difference between absolute and relative file names.

Related

Java InputStream with a shell script as input to Runtime.getRunTime().exec()

I am running a java program using a Jar file. Inside this packaged jar file I have my shell script. I understand that the best way to access the file would be through getResourcesAsStream because I can't access it via regular directory structures. So this is what I'm using:
InputStream input = this.getClass().getResourceAsStream("/script/sample_script.sh");
However, The only way I know how to execute this is if I go through the script line by line using a loop and bufferReader. I Statements like "If" or "While" loops get me an error. Is there a way to input the stream to achieve the desired results.
Here is my current code:
InputStream input = this.getClass().getResourceAsStream("/script/sample_script.sh");
BufferedReader brCmd = new BufferedReader(new InputStreamReader(input));
String cmd;
while ((cmd = brCmd.readLine()) != null){
proc = Runtime.getRuntime().exec(cmd);
proc.waitFor();
}
I've tried concatenating the whole file line by line to a string and using that but it doesn't seem to work. How can I get to make my script file run using inputStream? Any help would be appreciated
You could read the script file through InputStream and write it to a temp file under the system temp directory, and execute this file in following way:Runtime.getRuntime.exec("/bin/sh " + tempFilePath);
About reason to rewrite the script file to another temp file, you said you are executing your program by run the jar file directly, thus the script file is packed into the jar file and java won't unpack the jar file to the file system. To let the script file be accessible to cmd.exe, we need to rewrite the script file manually.
By the way, you could get the system temp directory path from system properties, or using apache common.io: FileUtils.getTempDirectory().

Controlling output file of a java jar using command line

I am using a .jar file, but unfortunatley as a black box, i.e. I do not know what exactly is in there nor how it all works.
I am sending commands to the Mac terminal from a Python script. I enter the following command:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt
This does what I need: analyses input using the 'black box' and creates and new file with analysis output. This new file is created in the folder where jarfile.jar is located.
I want to have this file put somewhere else upon creation.
I have tried using the > operator, specifying a path, e.g.:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt > /output/path/
this created a file in my desired location, but it was simply the message from Terminal, saying "The operation was carried out successfully" - the analysis results file was created in the same folder as before.
I tried %*> too, but it threw an error.
As a poor workaround I now have a function, which retrospectively finds and moves all the newly created files (analysis output) to my desired folder.
Is there a way to control the output files with the command line within the original command? Or is it something that is specified somewhere in my jar file? My problem is that editing it is not allowed.
I'm new to python. However, I may suggest to try few things, if they can work for you. Apology me, if does not work! I believe that you have already done the following step:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
Like, if you have a properly configured jar path, then can run jar directly.
Secondly, look at the cwd parameter (is used for executable). Include a cwd param as x
def run_command(command, **x):
with subprocess.Popen(command,...., **x) as p:
for run_command specify the path of either the working directory (possibly it should be) or the full system path. I'm not sure, just try both.
for outputline in run_command(r'java -jar jarfilepath', cwd=r'workingdirpath', universal_newlines=True):
print(outputline, end='')
Alternatively, you can try to run command from the directory in which you wish to store output file. Try: run the popen as
subprocess.Popen(r'directory of running command', cwd=r'workingdir')
where workingdir could be your current directory path.
If it does not work, try without r'. If still does not work, try doubling slash in the path like (C:\\ abc\\def)

Finding and opening any .exe file in C:/

I'm trying to create a small Java program that allows you to ask it to open an .exe file in a java window I created.
Here's a small example of what I want
User: Open chrome
Program: starts looking for a file called chrome.exe in C:/ and opens it
And that for any .exe file.
Is there any way to achieve this in Java?
Thanks!
exec(String command, String[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
command is the location of the .exe
envp can be null
dir is the directory of your .exe
With respect to your question it should be...
Runtime.getRuntime().exec("c:\\program files\\chrome\\chrome.exe", null, new File("c:\\program files\\chrome");
Process p = Runtime.getRuntime().exec("cmd /c start "+file.getAbsolutePath());
how to run the exe file
and to find files(search) have a read at Java: Find .txt files in specified folder

Running a .jar file in a command prompt from double click

I'll start of by saying Im on windows 7.
I have created a .jar file which executes fine from the command line using the - java -jar myJar.jar approach
But what I'm after is to be able to double click on the jar file and for it to open up the command prompt window and run in the command prompt as if i've just typed the java -jar myJar.jar line.
When I double click the jar file I do think it is running because a visual part of the java is appearing, but there is no command prompt window showing my console output.
After looking around I've come across people saying that javaw which is what the jar files are associated with don't have a console and that I need to associate jar files with java.exe instead of javaw.exe. I've tried this and it didn't seem to work.
Can anyone help? A step by step would be nice.
I had the same question and the bat file idea was genius and saved me a lot of time rewriting code. Thanks!(I would have upvoted,but apparently I don't have enough rep.)
Batch (or Bat) files are super easy to make.
Just put the java -jar YourFile.jar into notepad (if you're on windows), save as Title.bat, and put into the same folder as your jar.
presto! a program open-able by the general public.
This is IMHO not possible. You could open the console from the application itself, but that is OS-dependent. If you need the console open, you have to run the application from it as you already do.
If you want to display the command line you have to launch your jar with the command line.
java -jar MyJar.jar
I would do something like this:
(Tested in Widows XP with JRE 1.6, to support other OSs you should verify the path for each OS and select the appropriate console emulator (xterm, gnome-terminal... (check for existance and preference...)))
public static void main(String[] args) throws Exception {
if (args.length == 0) {
String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);//Adds extra slash (??) didn't know why
String decodedPath = URLDecoder.decode(path, "UTF-8");
System.out.println(decodedPath);
Runtime.getRuntime().exec("cmd /c start java -jar \"" + decodedPath + "\" actual_run");
}
else {
System.out.println("Hello World");
JOptionPane.showMessageDialog(null, "Hello World");
System.in.read();
}
}
Alternatively I suggest creating a bat file with this content :
java -jar yourjar.jar
This will launch your jar as well as open the command prompt automatically, all from a simple double click on a bat file.
(The bat file needs to be in the same folder as your jar file, else you need to specify the path to the jar, not just the jar name)
This is the easiest solution for beginners:
Open any text editor
write this two lines:
java "yourmainclassname"
pause
save that file as "name".bat
Run it with double click from windows GUI
(of course this new created .bat file must be in the same folder as the .class)
..but there is no command prompt window showing my console output.
No there wouldn't be a console for an executable Jar. You'll need to put that output in the GUI.
Check your MANIFEST.MF
Extract your "executable" jar file into a folder
find MANIFEST.MF in META-INF folder
check presence of this field:
Main-Class: YourMainClassHere
If this field dissapeared then open your original MANIFEST.txt for this point:
Main-Class: YourMainClassHere must end with a new line or carriage return
Warning: The text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Executing an external executable in a working directory containing spaces in Java?

I have a specific need to unrar files found in different subdirectories during execution of my program on Os x. I do this by calling the freeware command line tool unrar, which works very well.
However, unrar will always unrar files in the current working directory, which means that I have to specify a working directory for the executed process or get every unpacked file in my .jar home folder.
This is easy enough to do using either the processBuilder.directory(dir) or runTime.getRuntime().exec(args,null,dir) for example where dir is a File.
This works excellent but not when the working directory contains a space. As a short example:
File dir=new File("/Users/chargedPeptide/rar 2");
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar", "2/weather.rar"};
Process pr = Runtime.getRuntime().exec(cmd,null,dir);
int exitValue=pr.waitFor();
Will not work, while using: Process pr = Runtime.getRuntime().exec(cmd); instead will launch the command successfully but leave me with all of the files in the jars working directory.
Using processbuilder instead and using processbuilder.directory(dir); to set the directory
exits with the message:
Exception: Cannot run program "/Users/chargedPeptide/rar/unrar" (in directory "/Users/chargedPeptide/rar 2"): error=2, No such file or directory
Help? How do I handle the spaces? I've tried adding backslashes before the spaces to make them literal no help since the File object treats them like actual part of the path.
Edit: To make the whole thing a bit more clear:
1. I have a separate method that feeds the execute method a command and a directory to processbuilder, all directories are found by the previous method and exist. This works except when the dir contains a space.
2.I need to set the working dir or the command will execute in the wrong place.
3.Parsing the file object by:
dir=new File(dir.tostring.replace(" ","\ ");
to put a backslash in front of all spaces does not work since the java File object then looks for a path containing actual backslashes. No luck.
4.Using rt.exec instead of processbuilder dosen't help either.
Any ideas most welcome.
How about:
dir.mkdirs();
before launching the process.
This creates the missing directory.
Edit:
This looks strange.
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar", "2/weather.rar"};
If this was a shell you'd write:
unrar e -o+ "/Users/chargedPeptide/rar 2/weather.rar"
You actually have to put the .rar file in quotes, since otherwise it will be interpreted as 2 arguments to the process.
The way you've split 'cmd' will do exactly that, break the rar argument in two. Try:
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar 2/weather.rar"};
Not sure if it will work, but can you try putting a / at the end of the path.
i.e.,
File dir=new File("/Users/chargedPeptide/rar 2/");

Categories