How to use variable in Command prompt used by Java Program? - java

I have this program.
try {
Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("cmd /c dir");
Process pr = rt.exec("java -jar C:/sample/sample.jar D:/pdftest.pdf");
BufferedReader input1 = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input1.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
Here , process pr defines a command. Now my question, I want to replace the part "D:/pdftest.pdf" to a variable like
String pdfvariable="D:/pdftest.pdf";
So I should be able to replace hard coded value of "D:/pdftest.pdf" to pdfvariable.
Is it possible? Can anyone please explain it to me?
Thanks

String pdfvariable = "D:/pdftest.pdf";
Process pr = rt.exec("java -jar C:/sample/sample.jar " + pdfVariable);

Related

How to write and run terminal command to be execute in java program

String str;
Process p;
try {
String command = "wmctrl -l|awk '{$1=\"\"; $2=\"\"; $3=\"\"; print}'";
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((str = br.readLine()) != null) {
activeWindowtitles.add(str);
System.out.println(str);
}
p.waitFor();
p.destroy();
} catch (Exception ex) {
}
I am writing a java code to get all applications name in Linux system. I found a command to achieve this. I ran this command in Terminal and it works fine. But it is not working in Java code as i want only applications name instead of other details. The command is "wmctrl -l | awk '{$1=""; $2=""; $3=""; print}'"
I am getting full output after executing this in java code.
Please tell me how to write this command properly..
Thanks
Personally I would put the wmctrl command in a script and do something like this:
public static List<String> getRunningApps(String executablePath) throws IOException, InterruptedException {
final String ERR_LOG_PATH = "stderr.log";
List<String> result = new ArrayList<>();
ProcessBuilder pb = new ProcessBuilder(executablePath);
pb.redirectError(new File(ERR_LOG_PATH));
Process p = pb.start();
int exitCode = p.waitFor();
if (exitCode != 0) {
throw new RuntimeException(String.format("Error get apps. Check error log %s%n", ERR_LOG_PATH));
}
try (Scanner s = new Scanner(p.getInputStream())) {
while (s.hasNextLine()) {
result.add(s.nextLine().trim());
}
}
return result;
}
That way you can tweak it more easily and keep your code cleaner. The script I used was:
#!/bin/bash
wmctrl -l | awk '{$1=""; $2=""; $3=""; print}'

Java program for retrieving autosys status

Please tell me how to retrieve the status of autosys command from java program.
we can execute the commands using Runtime.getRuntime().exec(command) but how to get autosys status.
I am not sure about the autosys commend but if you can execute using the Runtime then you need to see the output of execution of command. If autosys will return something upon execution you will get it in out InputStream or error in ErrorStream in case of error.
Try something like this:
public static void printStream(InputStream is, String type){
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String args[])
{
String cmd = "command to execute";
Process proc = Runtime.getRuntime().exec(cmd);
printStream(proc.getInputStream(), "OUTPUT");
printStream(proc.getErrorStream(), "ERROR");
}
Process has a method exitValue() to get the exit value for the subprocess. exitValue
Example:
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("ls -al");
process.waitFor();
System.out.println(process.exitValue());

Open Command line + inputs for GUI

I am trying to write a java GUI in netbeans for executing a program on the command line, and currently have this piece of code assigned to a button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null)
{
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
This opens the terminal, however I would like to know how I should go about inputting commands into the terminal while still just pressing the button (ex: "ls", "cd", "javac" etc) Thanks!
UPDATE:
#Codebender My code now looks like this.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
new PrintStream(pr.getOutputStream).println("ls");
I am getting the error "cannot find symbol, symbol: variable getOutputStream, location: variable pr of type process" and a red line under getOutputStream. Any ideas?
#Codebender So should it be like this?
new PrintStream(pr.getOutputStream{println("ls")});
Use can use outputStream to write to the terminal. Wrap it up with a printstream to make things easier.
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
PrintStream ps = new PrintStream(pr.getOutputStream());
ps.println("ls" + System.lineSeparator());
// Follow with the reading of output from terminal.
If your Terminal.app is the default linux terminal, instead of opening a new one you can try,
Process pr = rt.exec("ls");
// Follow with the reading of output.

Java interact with cmd

Hi and sorry for my english...
I must interact in a windows terminal with a jframe...
This is code to start the cmd
try {
String command = "file.exe";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
output = pr.getOutputStream();
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(IOException | InterruptedException e) {
System.out.println(e.toString());
e.printStackTrace(System.out);
}
Then the jframe starts when exit from cmd line...
I need to start this in background and passing the output to the window...
How to ?
perhaps you should use Threads:
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Then, you would be able to interact with the process instance.

Running Bash from java does not work

I have this bash:
#!/bin/bash
# File to be tagged
inputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/Text.txt"
#inputfile="test/SampleInputs/longParagraph.txt"
# Tagged file to be created
#outputfile="test/SampleOutputs/NERTest.conll.tagged.txt"
outputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/1.Generate-Basic-Questions/Tagged-Named-Entites-Text.txt"
# Config file
#configfile="config/conll.config"
configfile="config/ontonotes.config"
# Classpath
cpath="target/classes:target/dependency/*"
CMD="java -classpath ${cpath} -Xmx8g edu.illinois.cs.cogcomp.LbjNer.LbjTagger.NerTagger -annotate ${inputfile} ${outputfile} ${configfile}"
echo "$0: running command '$CMD'..."
$CMD
When I run either java codes below they do not give any errors but they just show the bash file in my Eclipse Console, in other words they do not run the bash !! and the value for process.exitValue() is 1, by the way, my OS is CentOS, linux.
Firs JAVA code :
try {
Process process = new ProcessBuilder(command).start();
process.waitFor();
System.out.println(process.exitValue());
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
Second JAVA code :
String command = "/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/"
+ "SinaGolestanirad-Project/1.Generate-Basic-Questions/1.IllinoisNerExtended-DO-NOT-OPEN-BY-ECLIPSE/plaintextannotate-linux.sh";
StringBuffer output = new StringBuffer();
Process p;
try {
String[] cmd = new String[]{"/bin/bash",command};
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
I also checked the bash file permission and it is executable as a program.
How can I run the bash file? The bash should run another program written in java.
-- LeBarton what is the exit code?
Check the output of p.exitValue()
p.waitFor()
InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());
While (inputStreamReader.ready()) { System.out.println(inputStreamReader.read(); }
This will show you the error output. Add this to the bottom below the try.. catch.
You will see the output that you would see on the command line. It will help you narrow down the error.
I found a link which may help, if your bash read some environmental variables.
$PATH variable isn't inherited through getRuntime().exec

Categories