The code given below is the code that i try to run in eclipse which returns stdInput.readLine() as null when i try to run the command through command prompt it runs successfully what am i doing wrong?
public class Recognize {
public String Recog(String name)
{ try {
String command="java -cp .;C:\\mywork\\Speaker\\marf-0.3.0-devel-20070108-fat.jar SpeakerIdentApp --ident C:\\mywork\\Speaker\\testing-samples\\"+name+".wav";
Process proc = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
name = "";
String s ;
System.out.println(stdInput.readLine());
// read the output from the command
// System.out.println("Here is the standard output of the command:\n");
while ((s=stdInput.readLine()) != null){
// System.out.println(s);
String recog = s;
// System.out.println(recog);
String ex = stdInput.readLine();
// System.out.println(ex);
String sb = stdInput.readLine();
// System.out.println(sb);
if ( recog.equalsIgnoreCase(ex))
{//System.out.println("ACCESS GRANTED");
name = recog;
// System.out.print(recog);
}
else if (ex.equalsIgnoreCase(sb))
{//System.out.println("ACCESS GRANTED");
name = ex;
// System.out.println(ex);
}
else {//System.out.println("ACCESS DENIED");
name = "";
}
it must be because eclipse default path is not set by you so try setting eclipse default path according to your requirement
Related
I have to execute a command from Java program on Unix platform.
I am using Runtime.getRuntime() for it.
However, the problem is that my command is interactive and asks for certain parameters at runtime. For e.g., the command is createUser. It asks for userName as the runtime.
bash-4.1$ createUser
Enter the UserName:
How can I handle such scenario so that the user name is entered at runtime from Java program?
try {
Process proc;
proc = Runtime.getRuntime().exec(cmd, envp);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
sb = null;
}
I heard that it can be done through expect. But How can I do it in Java?
Get also the standardOutput from proc. All you write in that standardOutput goes to the command
Send the username to standardOutput and don't forget to send the \n too.
You can check what was the last line of input steam and when you detect the prompt for user input input write to the output steam your value.
try {
Process proc;
proc = Runtime.getRuntime().exec(cmd, envp);
final BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
final PrintWriter stdOutput = new PrintWriter(proc.getOutputStream());
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if (s.equals("Enter your username")) {
stdOutput.println("MyUsername");
stdOutput.flush();
}
sb.append(s);
}
} catch (final Exception e) {
e.printStackTrace();
sb = null;
}
(removed the error stream for simplicity)
Note that this works only if the prompt ends with a new line.
If the prompt has no new line (eg. Username: <cursor here>) you can try just writing the value at the start:
...
final PrintWriter stdOutput = new PrintWriter(proc.getOutputStream());
stdOutput.println("MyUsername");
stdOutput.flush();
...
But if the the command clears the buffer this will no work, in that case (rare case) you have to change the way you read from the stream (eg. instead of lines, read bytes)
I am trying to execute a shell script that takes input with Java.
Here is my code so far...
OutputStreamWriter output;
Process p = new ProcessBuilder(new String[]{"sh", "-c", "/data1/Abhishek/hello.sh"}).start();
output = new OutputStreamWriter(p.getOutputStream());
String line = "";
String text = "";
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if(line.equals("Enter Your Name: ")) {
String password = "password";
output.write(password);
output.write('\n');
output.flush();
}
text += line;
text += "\n";
}
input.close();
try {
p.waitFor();
} catch (InterruptedException e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
}
Here is the shell script..
#!/bin/bash
read -p "Enter Your Name: " username
echo "Welcome $username!"
However it is not working. The script is still waiting for the input...
What am I doing wrong?
I want to get terminal history
So I did this
Runtime rt = Runtime.getRuntime();
pr = rt.exec("/bin/bash -c \"history -c\"");
pr.waitFor();
rt.exec("/usr/bin/xterm");
but there is problem with pr = rt.exec("/bin/bash -c \"history -c\""); , it's not clearing the previous history nither of xterm nor my normal terminal.
Also when I try to print the history it returns nothing (no errors)
p = Runtime.getRuntime().exec("/bin/bash -c \"history\"");
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("printing");
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
I also tried
String[] commands = new String[]{"/bin/sh","-c", "history -c" ,"xterm"};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
} catch (IOException e1) {
e1.printStackTrace();
}
still not clearing history.
You can remove the history file yourself by getting the $HISTFILE environment variable. This will always get the correct history file for different shells. I believe the issue you're having is that the you may be using a different shell or have changed your history file location.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RemoveShellHistory {
public static void main(String[] args) {
RemoveShellHistory obj = new RemoveShellHistory();
final String shellPath = System.getenv("SHELL");
String shell = shellPath.substring(shellPath.lastIndexOf("/")+1, shellPath.length());
final String home = System.getenv("HOME");
String command = "rm -v " + home + "/." + shell + "_history";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
Assuming that your java app runs by the same user possessing the .bash_history file:
To delete.
new File(System.getProperty("user.home"), ".bash_history").delete();
To clean (Handle the checked exception at your will).
FileWriter writer = new FileWriter(
new File(System.getProperty("user.home"), ".bash_history"));
writer.write("");
writer.close();
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);
}
}
I am able to execute commands from the commandline with the code below. If a pass a working command to the code it processes and give me a return value. What I need is to get the response from the command line when it does not process correctly. So if I pass a copy command to the prompt and it executes I get a value. If I pass a copy command to the prompt and it fails I get no value. Here is my code
public String CommandLineExecuteReturn(String loc)
{
String returnValue = "";
String outValue = null;
try
{
Process p = Runtime.getRuntime().exec("cmd.exe /c "+ loc);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
;
returnValue = line;
}
}
catch (IOException e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
returnValue = stacktrace;
}
return returnValue ;
}
You also need to redirect the error stream (p.getErrorStream()) - note that reading from both streams will require two threads.
Alternatively and more easily, you could use a ProcessBuilder and call its redirectErrorStream(true) method.
See also this post.