Running terminal commands throug java - java

I have to execute two commands in terminal from my java program. Here is the java code that I am using :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 hello.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// 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();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
My hello.cpp file is stored in the home directory. When I compile the java program it gets compiled but while running it it is throwing exception. Here's the output which I am getting :
Exception occurred java.io.IOException: Cannot run program "aarch64-
linux-g++": error=2, No such file or directory

Try to replace using following lines in your code,
String compileCommand = "g++ -std=c++14 hello.cpp";
String runCommand = "./a.out";
And keep the .cpp file in same directory where the .class file lies.

Related

How to execute a python file with some arguments in java

String command:
python FileName.py <ServerName> userName pswd<b>
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line + "\n");
}
Code is neither terminating nor giving the actual results. ...
This May Be Helpful !
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.
#!/usr/bin/python
import sys
print 'Number of Arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.arv)
print('This is Python Code')
print('Executing Python')
print('From Java')
if you save the above file as script_python and then set the execution permissions using
chmod 777 script_python
Then you can call this script from Java Runtime.exec() like below
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ScriptPython {
Process mProcess;
public void runScript(){
Process process;
try{
process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"});
mProcess = process;
}catch(Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = mProcess.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8));
String line;
try{
while((line = reader.readLine()) != null){
System.out.println("stdout: "+ line);
}
}catch(IOException e){
System.out.println("Exception in reading output"+ e.toString());
}
}
}
class Solution {
public static void main(String[] args){
ScriptPython scriptPython = new ScriptPython();
scriptPython.runScript();
}
}

When I am running java program manually from terminal it is working fine but it is not working when i am running from eclipse

My program is not running from eclipse but it is running through terminal in ubuntu.
Below is the shell script that i am running in java
#!/usr/bin/env bash
# Running sqoop commands
s="$(sqoop help)"
echo "$s"
Below is the java code
package flexibility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Flex {
public static void main(String args[]) throws Exception {
String s = null;
String line = "";
String sqoopCommand = "sqoop help";
try {
Process p = Runtime.getRuntime().exec("/home/avinash/sqoop.sh");
p.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stdInput.readLine()) != null) {
output.append(line + "\n");
}
while ((line = stdError.readLine()) != null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
error message :
/home/avinash/sqoop.sh: line 5: sqoop: command not found
Try with the command "sh /home/avinash/sqoop.sh". I feel since the ubuntu isn't aware what kind of file it is,It's clearly throwing command not found error.
The error message is from your script. Not from Eclipse.
Eclipse (or the JVM to be more precise) does not know about the environment variables or working directory of the script. In contrast: If you run the script from command line environment variables (e.g. PATH) or working directory are known.
You can use method Runtime.exec(String command, String[] envp, File dir) to specify this in your Java code. So I guess this should work:
Process p =
Runtime.getRuntime().exec("/home/avinash/sqoop.sh", null, new File("/home/avinash/"));

Executing "$ aarch64-linux-objdump -d a.out' in terminal throug java

I have made a cross compiler using gcc. Now I want the compile and run commands to be executed in a terminal through java program. Here is the code that I am using for this :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 test.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// 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();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
Now my first command is executing since I could see the a.out file being generated. The second command should dump the memory contents of file and it should print in in terminal but I am not seeing any output. Can anyone tell where I am going wrong?

Java ProcessBuilder not able to run Python script in Java

null from bfr.readLine()
However, there is no problem if I run the python file directly on terminal by firing:
python C:/Machine_Learning/Text_Analysis/Ontology_based.py
The last line in my Python script is >> print(data)
The result of the following code is:
Running Python starts:
First Line: null
Picked up _JAVA_OPTIONS: -Xmx512M
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder("python", pythonPath);
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}
Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : "+exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}
Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.
I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.
try {
Process p = Runtime.getRuntime().exec(
"python D://input.py ");
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
p.waitFor();
} catch (Exception e) {
}
try {
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python", "D://searchTestJava//input.py");
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
} catch (Exception e) {
System.out.println(e);
}
I tried this one. This script runs a python file with the argument in Java. It also logs about which line, your program is executing. Hope this Helps.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Test {
public static void main(String... args) throws IOException {
ProcessBuilder pb =
new ProcessBuilder("python","samples/test/table_cv.py","1.pdf");
pb.redirectErrorStream(true);
Process proc = pb.start();
Reader reader = new InputStreamReader(proc.getInputStream());
BufferedReader bf = new BufferedReader(reader);
String s;
while ((s = bf.readLine()) != null) {
System.out.println(s);
}
}
}

executing a java program in another java program using Runtime.exec() function

The following code snippet i had given is using exec function and executes hello program (simple "hello world" printing java program). But as soon as i execute the main program, print statement of instream.readline() simply returns NULL. Please try to sort out the problem. Hope the explanation is clear.
CODE:
Process process2=null;
BufferedReader inStream=null;
try
{
process2 = Runtime.getRuntime().exec("java hello");
}
catch(IOException e1)
{
System.err.println("Error on exec method");
e1.printStackTrace();
}
try
{
inStream = new BufferedReader(new InputStreamReader(process2.getInputStream() ));
System.out.println(inStream.readLine());
}
catch(IOException e1)
{
System.err.println("Error on inStream.readLine()");
e1.printStackTrace();
}
First of all your hello.java should be already compiled n the class file should present in the current directory where the program is located.
And for getting errors, you can get error stream from process class's object.
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String s="";
while ((s = stdError.readLine()) != null)
System.out.println(s);
Working with Eclipse/java7/windows
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessDemo {
public static void main(String[] args) throws Exception {
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
Runtime run = Runtime.getRuntime();
Process pr=run.exec("javac -d "+ dir +"\\src "+ dir+"\\src\\HelloDemo.java");
pr.waitFor();
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
String s;
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
System.out.println(s);
//read output
while ((line=buf.readLine()) != null)
System.out.println(line);
pr.destroy();
Runtime run1 = Runtime.getRuntime();
Process pr1=run1.exec("java -cp "+dir+"\\src HelloDemo");
BufferedReader stdError1 = new BufferedReader(new InputStreamReader(pr1.getErrorStream()));
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pr1.getInputStream()));
//interpretting file n executing it line by line :D :P
pr1.waitFor();
String temp;
// read any errors from the attempted command
System.out.println("\n\nHere is the standard error of the command (if any):\n");
while ((temp = stdError1.readLine()) != null)
System.out.println(temp);
//read output
System.out.println(buf1.readLine());
while ((temp=buf1.readLine()) != null)
System.out.println(temp);
}
}

Categories

Resources