This question already has answers here:
Running MATLAB function from Java
(5 answers)
Closed 9 years ago.
sorry if I ask a simple question but I would like to ask whether it is possible when executing a java source to have code in it which makes an independent Matlab programme run (not only to execute Matlab code in java) ? I think this is also general question whether you can start other programmes in the process of execution of your code in Java.
Thank you.
Best,
M
I know you can run external Programmes like this:
import java.io.*;
public class CommandExection {
public CommandExection(String commandline) {
try {
String line;
Process p = Runtime.getRuntime().exec(commandline);
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
public static void main(String argv[]) {
new CommandExection("c:\\Yourprogram.exe");
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Goal: to initialise a JVM(2) from a separate JVM(1) using ProcessBuilder, capturing the resulting output from JVM(2) and displaying the result within a JTextArea in JVM(1).
Situation: able to launch JVM(2) from within JVM(1) and capture the resulting output from JVM(2) to a JTextArea within the JVM(1).
Problem: the JVM(2) will not respond to input until JVM(1) is terminated.
Thread inside VJM(1) that starts JVM(2):
Runnable runnable = () -> {
try {
JVMBooter.startSecondJVM();
} catch (Exception ex) {
Logger.getLogger(MyMenu.class.getName()).log(Level.SEVERE, null, ex);
}
};
Thread t = new Thread(runnable);
t.start();
JVMBooter source code:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class JVMBooter {
public static void startSecondJVM() throws Exception {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "startscript.bat");
File dir = new File("D:/Server");
pb.directory(dir);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
( (line = reader.readLine()) != null && ! line.trim().equals("--EOF--")) {
OutputFrame.textArea.append(line + "\n");
}
}
}
The JVM(2) is started within the startscript.bat file with:
java -jar server.jar
Depending on the situation it may be necessary to read the error stream instead of the input stream, e.G. if your second java call is -version or the program you call only writes to stderr instead of stdout getting the Error Stream is the correct approach.
I wrote this MCVE:
import java.io.*;
public class Starter {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("./dosomething.sh");
File dir = new File(new File(File.listRoots()[0], "tmp"), "2jvm");
pb.directory(dir);
Process p = pb.start();
BufferedReader read = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ( (line = read.readLine() ) != null) {
System.out.println("line: " + line);
}
}
}
and in 'dosomething.sh' this:
echo before
java -version
echo after
when I use p.getInputStream I would get the 'before' and 'after'. When I use p.getErrorStream I get the Java Version Information.
That might be true for you too. I suggest you add echo lines in your batch file to see if they get printed out.
I also wrote a simple hello world and when I called that from dosomething.sh it got printed to the input stream as expected. It is a weird quirk of -version to write to stderr.
For completeness here is the Hello World I used (it has waits to simulate a longrunning server process):
public class Caller {
public static void main(String[] args) {
synchronized(Caller.class) {
for(int ii = 0; ii < 10; ii++) {
try {
Caller.class.wait(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Hello world! " + ii);
}
}
}
}
I am new in java, so my question can be muddled.
I tried to run some process from java. It is xmr-stack miner. I use code like that:
package com.company;
import java.io.*;
public class Main {
public static void main(String[] argv) throws Exception {
try {
String line;
Process p = Runtime.getRuntime().exec( "D:\\xmr-stak.exe " +
/* some arguments */ );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
}
}
It works perfect for common things.
But I faced an issue that I have no output after some point in xmr-stak. As far as I understand at some point this app create child process. And I didn't see output produced by this child process.
But after very long time working (10+ minutes) I got my output for all this time.
It is looks like some output buffer was flashed after overflow.
Now I want to understand how to get required output more often in java.
From other side I wrote same logic in c++
(Based on this question SO arswer)
And I got my output in time.
Runtime.exec is obsolete. You can replace your entire program with a few lines that use ProcessBuilder:
ProcessBuilder builder = new ProcessBuilder("D:\\xml-stak.exe",
arg1, arg2, arg3);
builder.inheritIO();
Process p = builder.start();
p.waitFor();
You don’t need to read the process’s output (and therefore don’t have to worry about buffering), because inheritIO() makes that output appear in your Java program’s output.
You also don’t need to catch any exceptions, since your main method already has throws Exception.
This question already has answers here:
Capture SIGINT in Java
(3 answers)
Closed 7 years ago.
I'm trying to run the following Java code which is supposed to automatically restart itself when I kill it via CTRL + C on windows command-line :
import java.net.*;
import java.io.*;
public class LineRunner extends Thread {
public static void main(String[] args) throws InterruptedException, IOException{
try {
for (int i = 0; i<10000000; i++) {
Thread.sleep(200);
System.out.print("hithe");
}
}
catch( InterruptedException ioex) {
String[] command = {"C://Program Files//Java//jdk1.7.0_02//bin//java.exe", "LineRunner"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process exec = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
System.out.println("Process exited with " + exec.waitFor());
}
}
}
But when I kill from command line (via CTRL + C ) , it does not restart the program as I wish.
Any tips appreciated, thanks
You need use addShutdownhook to listen the program exit and you can restart your program in there.
Ctrl-C will exit the JVM as has already been discussed in comments.
This question already has answers here:
How to run Linux commands in Java?
(9 answers)
Closed 3 years ago.
I am trying to call my rrdtool cmd from a java class, not sure how to go about it.
I have tested my RRDTool cmd from my terminal and it is successful, see below.
rrdtool update mydb.rrd 1385056701:6:5
How do i execute this cmd from a java class?
You can use the below command format to run your Linux command.
Runtime r = Runtime.getRuntime();
Process p = r.exec(yourcmd);
Please go through Running unix command from Java and Unable to run Unix command in Java-Stackoverflow
Hope you get your answers here.
try this
public class ShellTest {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
// Get runtime
java.lang.Runtime rt = java.lang.Runtime.getRuntime();
// Start a new process: UNIX command ls
java.lang.Process p = rt.exec("ls");
// Show exit code of process
System.out.println("Process exited with code = " + rt.exitValue());
}
}
also check here for more details
Try like this(As answered by paxdiablo):
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
Also check java.lang.Runtime.exec for details.
Executes the specified string command in a separate process.
This is a convenience method. An invocation of the form exec(command)
behaves in exactly the same way as the invocation exec(command, null,
null).
You can use Runtime#exec for this purpose. If you want a Java-like control over the started process, there is a great library called zt-exec that makes handeling processes much easier. The ProcessBuilder is also offering a minor API improvement over Runtime#exec that ships with the Java standard library.
Something you have to take care of is that Java processes come with very little buffer for the in- and output streams what blocks processes once these buffers run full. This happens silently. zt-exec can help you with that.
You can have a look at :
https://github.com/OpenNMS/opennms/blob/master/opennms-rrd/opennms-rrd-rrdtool/opennms-rrdtool-api/src/main/java/org/opennms/netmgt/rrd/rrdtool/JniRrdStrategy.java
for a real life use of rrdtool in java.
Or at
https://code.google.com/p/rrd4j/
For a native version of rrdtool in java.
I runned my rrdtool command in java program as follow:
Process p = null;
try {
ProcessBuilder pb = new ProcessBuilder("/usr/bin/rrdtool","lastupdate", rrdPath);
pb.redirectErrorStream(true);
p = pb.start();
int exitVal = p.waitFor();
if (exitVal == 0)
System.out.println("exitVal of rrdLastUpdate is Successful");
else
System.out.println("exitVal of rrdLastUpdate is Abnormal");
} catch (Exception e) {
System.out.println("Problem in executing rrdlastupdate()");
e.printStackTrace();
}//end of try-catch
I hope this be useful for U :) I worked with some other rrdtool commands in java. if you need more help, I will be happy to help.
This question already exists:
redirection in exec() method in java
Closed 9 years ago.
I have to execute a program RegAlloc.java with input redirection (4.miniIR file)
try{
String s="java -classpath MiniRA/ RegAlloc < MiniRA/4.miniIR";
Process pro2 = Runtime.getRuntime().exec(s);
BufferedReader in =new BufferedReader(new InputStreamReader(pro2.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
text+=line;
text+="\n";
System.out.println(text);
}
System.out.println(text);
}
catch(IOException e) {
System.out.println("not Okey");
}
but I don't get the proper result; the output window is just displayed and will not terminate the program. Can anybody help me find the error?
if its just regarding the process is not terminated, you can force terminate it using pro2.destroy() in the code, at the end of try block.
You must read from stdin in your process. But you try hook stdin of external process. Try replace it:
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));