Executing a .exe or .linux file in Java during Run time - java

I am trying to create a function within a Java Class that can execute a .exe or a .linux file during runtime.
The program is espresso.exe (for Windows OS) and espresso.linux for (Linux based systems)
Typically, the way to run the program is by going to command line, and going to the folder in which the executable is stored and typing:
(in Command Prompt)
espresso A0.txt > m.txt
or espresso A0.txt (which returns the output in cmd)
(in linux Terminal)
./espresso.linux A0.txt > m.txt
or ./espresso.linux A0.txt (which returns the output in the terminal window)
Here A0.txt is the input argument and m.txt is the file that espresso creates.
I have stored A0.txt and espresso.linux and espresso.exe under a folder src/resources
I tried the following:
ProcessBuilder pb = new ProcessBuilder("./src/resources/espresso.exe","src/resources/A0.txt",">src/resources/m.txt");
try {
Process p = pb.start();
}catch (IOException ex) {
Logger.getLogger(NetSynth.class.getName()).log(Level.SEVERE, null, ex);
}
I also tried:
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("src/resources/espresso.linux src/resources/A0.txt > src/resources/m.txt");
int waitFor = p.waitFor();
Both of them fail to identify the file to be executed and do not run the command. I understand there may be many errors in the 2 approaches. I could use some help to figure out the approach and the code to be written to run the executable file.
Also, is there a path to be mentioned to run espresso.linux? Will /src/resources/espresso.linux suffice?
Thanks in advance.

You can't do standard output redirection like this (because the ">" sign is interpreted by the OS shell), see this answer for a working solution: ProcessBuilder redirecting output
Since Java 7 there is a Java-only solution in order to achieve redirecting: http://tamanmohamed.blogspot.co.at/2012/06/jdk7-processbuilder-and-how-redirecting.html

The > is a shell syntax. If you want to redirect the output to a file you need to use a shell or read the output and write it to a file yourself.
The way you have used > it is just another argument.

Related

who i can run shell (.sh) scripts in Centos X64 and read output?

I'm using Intellij IDEA and i'm trying to run a shell script with arguments, and read the result of the execution.
this script is on my java SRC packge,
myScript.sh run a compiled c program
String[] cmd = { "/bin/bash", "-c", "myScript" };
Runtime.getRuntime().exec(cmd);
i resolved this by making a copy of myScript.sh in /ect/bin.
so this make my script as an environment path and give me the ability to read all the out put or add supplement arguments.
no changes has been made
on my Java code
.
Use ProcessBuilder:
Process process = new ProcessBuilder(cmd).start();
Then process.getInputStream() gives you access to the process standard output (stdout) which you can read as usual; process.getErrorStream() allows to read standard error (stderr).
Also you can do process.waitFor() to wait for the project to finish.
Note that to read anything from the stdout of a process you need to wait for the process to finish (or read it in a loop) and not just finish your main program.

Check if jar is running or not

I would like to check whether a jar of mine is running on the users system, to then relaunch if it is closed.
I am aware of the command jps -l which makes it possible to check the current running jars. Only problem is that for that line to work, it requires the user to have a JDK installed. So I was then wondering whether or not there is an equivalent to the jps -l line, which doesn't need a JDK or anything, but just checks whether a specific jar is running.
In the past I have also used the line cmd /c tasklist for Windows and the line top -F -R -o cpu for Mac. To check whether an app or exe was running, but that doesn't really seem to be working. When running the tasklist line on Windows and I then check for an exe called "myApp", it doesn't find it. Even though it might be running. Otherwise this would have been a perfect method, to check for a running app, exe or jar.
Here is an example code of how I tried to use the tasklist command to check for a specific executable.
try {
String procss;
Process pRun = Runtime.getRuntime().exec("cmd /c tasklist");
BufferedReader input = new BufferedReader(new InputStreamReader(pRun.getInputStream()));
while ((procss = input.readLine()) != null) {
if(!procss.contains("myApp"))
{
//Runtime command to launch exe or app.
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
Basically I would like to just edit the code above, to have a command line, of which is able to actually check whether the exe, app or jar is running. Maybe there is an alternative to cmd /c tasklist and top -F -R -o cpu, which is able to get all processes running on a pc and not just .exe or .app
On windows, you could use the wmic command to get the command line parameters a program was launched with.
For example, using wmic process where "name like '%java%'" get commandline,processid (basically just means "get the PID and command line arguments of process with a name like java") gives me this output for a test program:
616
"C:\Program Files\Java\jre1.8.0_111\bin\javaw.exe" -jar "A:\Programmering\Java\Pong\out\artifacts\Pong_jar\Pong.jar"
As you can see, you can get the location of the jar file which is running (which you could then use to check if it's your program). In this case, I just launched it by double clicking the jar file, you may get different outputs if you launch it in a different way, but there should always be something you can use to identify the java process (like a main class or jar file).

Runtime.getRuntime().exec() doesn't execute some commands

I'm beginner at java and have some problems. I've read several topics about this theme but none of them worked for me. Here is my code:
try
{
Console console = System.console();
String command;
while(true)
{
command = console.readLine("Enter input:");
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
catch(Exception e) {}
So what I'm trying is to make a java program and run terminal commands in it(I'm using linux). This program works with commands like "ls" "ps ef" and others but it doesn't work when I type "cd". I know that cd makes different process and should be used this way: "Runtime.exec(String command, String[] envp, File dir)". My questions is:
How to make my program run all kinds of terminal commands? Sorry if question sound silly. Thank you.
The cd command is a shell built-in command. There is no shell when you run a command via exec(...). Indeed, if you try to find a cd command in any of your system's bin directories, you won't find one ... because it is impossible to implement as a regular command.
If you are trying to use cd to change the current directory for the JVM itself, that won't work because a command can only change the current directory of itself and (after that) commands that it launches itself. It can't change its parent processes current directory.
If you are trying to use cd to change the current directory for subsequent commands, that won't work either. The context in which you set the current directory ends when the command finishes.
In fact, the right way to change the directory for a command run using exec is to set it via the ProcessBuilder API itself.
How to make my program run all kinds of terminal commands?
You can't. Some of the "terminal commands" only make sense as shell commands, and that means you need a shell.
I suppose, you could consider emulating the required behaviour in your Java code. That would work for cd ... but other commands are likely to be more difficult to cope with.
(For what it is worth, it is possible to implement a POSIX compatible shell in Java. It is just a LOT of work.)
you've actually got to run the console you want to use (ie sh, csh, bash, etc) and then use the process OutputStream to feed in commands
I think the Problem is not your Code, the command is the problem...
what do you want to see if your command is cd ??
In Background it changes the path but you get nothing back.
Changing the Directory is not processing any output.
This worked for me:
Runtime.getRuntime().exec(new String[]{ "/system/bin/sh", "-c", "ls -l" } );

How do I open a .bat containing a GUI in a java program in Linux?

everyone. I'm quite new here so please be tolerant if I make any mistakes.
I have a .bat file containing a command line to open up a .jar file that contains a program that has a GUI in it. The only line that's in the .bat file is:
java -jar "NewServer.jar"
I've been trying to use Runtime() to get this to run, but most the instructions I find to open a .bat file in a java program are for Windows. I'm currently using Fedora 12 (don't tell me to upgrade, I can't) if that makes a difference and programming using Eclipse. I also found this ProcessBuilder thing, but I couldn't get it to work so unless you have very explicit directions on how to use it, please don't include it in your answer. I would much rather use Runtime. It looked simpler.
Here's my code to test using Runtime in a java program. I'm hoping that if I can get this to work, I can get it to work in my real program.
import java.io.IOException;
public class testbat {
public static void main(String[] args) {
Process proc = null;
try {
proc = Runtime.getRuntime().exec("./ myServer.bat");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Cool");
}
The last line is just there for me to see if the program actually ran in case the GUI doesn't open. Also, I've already tried many combinations of things to include in the area after ".exec". I've tried using a path like "~/user/workspace/ProjectServer/dist/myServer.bat" to no avail.
I also already know that .bat files are for windows, but I'm able to execute it in linux, so I don't know if that makes a difference. I also tried using a .sh file the same way and it didn't work.
Please bear in mind that I'm not that great at Java, but I had to use it for this particular program, so if your answers could be really descriptive that would be awesome.
Just take that line out of the bat file, and run it. Yo're making it too hard.
$ java -jar "NewServer.jar"
will work. The quotes aren't necessary, so
$ java -jar NewServer.jar
will work as well. If you want to have the equivalent of your bat file, create a file named, say, run_newserver containing that line. Change its mode to executable:
$ cat > run_newserver
java -jar NewServer.jar
^D
$ chmod a+x run_newserver
$ ./run_newserver
Ideally, since you shouldn't have scripts without comments, do this. In your favorite editor, create a file run_newserver containing
#!/usr/bin/env bash
java -jar NewServer.jar
and chmod that. The line with #! -- often called a "shebang line" -- is UNIX magic that lets you say what interpreter you want. The program env in usr/bin finds your program and runs it (needed because different systems put bash in different directories.)
You could even put explanatory comments in the file too.
I'm a little unclear why you want to use Runtime#exec to run it at all -- it seems you'll just need a shell script to start that program.
Why are you using Java to run a Batch file, that in turn runs a Java program? Why have Batch in the loop at all? Just put the jar in your classpath and call it directly.
Batch (.bat) files are only for Windows environment. So, Try using shell script
Process proc = Runtime.getRuntime().exec("myServer.sh");
Just open up terminal and do this
vi /dir/to/exec/exec.sh
tap "i" and write this
#!/bin/sh
java -jar "NewServer.jar"
or if you want to run it in the background
#!/bin/sh
java -jar "NewServer.jar" & > /tmp/JavaServer.log
hit esc and type ":wq" and you have saved the file.
type this into the terminal
chmod +x /dir/to/exec/exec.sh
this give executable privileges and then you should run the file like
sh /dir/to/exec/exec.sh
Process is only initialized by your first call. You need to run:
proc.waitfor();
to get it to actually run your app.

Java : how to determine disk space on Windows system prior to 1.6

I want to determine the available disk space on windows. I don't care that my code is not portable. I use this :
String[] command = {"dir",drive};
Process process = Runtime.getRuntime().exec(command);
InputStream result = process.getInputStream();
aiming to parse the result from a "dir C:" type of call, but the String I get from the command line call is as if I called dir with a /W option (not giving any information about file sizes or disk usage / free space). (Although when I launch dir C: directly from the command line, I get the expected result, so there is no dir particular setup on my system.) Trying to pass a token /-W or on any other option seems not to work : I just get the name of the folders/files contained in the drive, but no other information whatsoever.
Someone knows a fix / workaround ?
NOTE:
I can't go along the fsutil route, because fsutil does not work on network drives.
It sounds like your exec() is finding a program called "dir" somewhere in your path because with your String[] command as it is I would otherwise expect you to get an IOException (The system cannot find the file specified). The standard dir command is built into the cmd.exe Command Prompt and is not a standalone program you can execute in its own right.
To run the dir command built into cmd.exe you need to use the /c switch on cmd.exe which executes the specified command and then exits. So if you want to execute:
cmd /c dir
your arguments to pass to exec would be:
String[] command = { "cmd", "/c", "dir", drive };
If you don't care about portability, use the GetDiskFreeSpaceEx method from Win32 API. Wrap it using JNI, and viola!
Your Java code should look like:
public native long getFreeSpace(String driveName);
and the rest can be done through the example here. I think that while JNI has its performance problems, it is less likely to cause the amount of pain you'll endure by using the Process class....
Apache Commons has FileSystemUtils.freeSpaceKb() that will work cross platfrom etc etc

Categories

Resources