This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java external program
I am trying to wrtie a program to write a command on a command line,
for example;
ipconfig
and then get the response of the command so I want to both write command to a command line and get its response. I have searched about it on the net and saw that apache cli is used to do this in Java but actually I did not clearly get how it can be done. Can you please help me about my situation with a few line of codes or tutorials about both writing and reading commands please?
Thank you all very much
You could start it as a Process and capture the InputStream of the process as described here:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ipconfig"); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Edit: I copied this code from above link, but the code seems wrong. Don't you need the output stream for this? Edit2: no.
getInputStream()
Gets the input stream of the subprocess. The stream obtains data
piped from the standard output stream of the process represented by
this Process object.
Nice naming convention...
See Process and ProcessBuilder classes.
Specifically, you would create a Process. Process.getOutputStream() gives an InputStream, from which you read what the process's output. You also need to read Process.getErrorStream() for any errors that the process reports.
Try this for inputting the user value.
java.util.Scanner input = new Scanner( System.in);
System.out.println("Please Enter your Name: ");
String empName = input.nextLine();
Related
This question already has answers here:
Executing another java program from our java program [duplicate]
(3 answers)
How to save a shell script's echo output within Java [duplicate]
(2 answers)
Closed 5 years ago.
I was tried to get OSM data from my local overpass API. There are four steps to get OSM data.
run the binary file /srv/osm3s/bin/osm3s_query
once the osm3s_query is running, you'll see this messageencoding remark: Please enter your query and terminate it with CTRL+D.
input your query <query type="node"><bbox-query n="51.0" s="50.9" w="6.9" e="7.0"/><has-kv k="amenity" v="pub"/></query><print/>
press ctrl+D and get the OSM results
my code as below:
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("/srv/osm3s/bin/osm3s_query");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null)
System.out.println(line);
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
The process will hang on step 2 after shown the message encoding remark: Please enter your query and terminate it with CTRL+D.. I have no idea how to give the process the query string.
Anybody has some idea?
OutputStreamWriter output = proc.getOutputStream();
output.write(yourQuery);
output.write(4); // that's ctrl-d
output.flush();
Firstly -- this is a pretty fragile way to interact with the Overpass API. Since Overpass is an XML-over-HTTP API, and Java has lots of XML and HTTP libraries, there are plenty of ways to do it in native Java. OpenStreetMap provides examples - for example http://wiki.openstreetmap.org/wiki/Java_Access_Example
This is probably easier, and certainly more robust, than calling an external command.
There are also higher level Java libraries: http://wiki.openstreetmap.org/wiki/Frameworks
For the general case of running a process, writing to its stdin and reading from its stdout, since Java 1.5 it's best to use ProcessBuilder to create your Process.
Once you have a process, you can use getInputStream(), getOutputSteam() and getErrorStream() to get the relevant streams (in the builder, if you like, you can make stderr go to stdout).
It's possible to get into a deadlock when reading and writing these streams - in many situations you'll need to either use non-blocking IO classes or create separate threads for reading and writing.
I've stored my python code in file and then input is passed through input.txt.
String rollno="13F127";
String file="add";
Process p = Runtime.getRuntime().exec("C:\\Python34\\python C:\\Users\\Raga\\Documents\\"+rollno+"\\"+file+".py < C:\\Users\\Raga\\Documents\\"+rollno+"\\input.txt");
When I run it using jsp file, it takes long time to load and output didnt come. Please help me with this.
I've read this process output using buffered and input reader.
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Please help me with this!
Do not use redirections (<, >, or |) with exec!
The redirections are read and translated by the interactive shells (here cmd.exe) where they read a command from their standard input. The shell then opens the relevant files and calls the program with redirected standard streams.
exec just does this last part, and passes the < ...input.text as two arguments to the Python program... that do not processes them and also passes them to the script that do not process them either! So the child tries to read on standard input, and keeps waiting here.
So you should:
use ProcessBuilder which according to Runtime javadoc is now the preferred way to start a process with a modified environment
redirect input stream for the subprocess to the file
More or less:
ProcessBuilder pb = new ProcessBuilder("C:\\Python34\\python",
"C:\\Users\\Raga\\Documents\\"+rollno+"\\"+file+".py");
pb.redirectInput(Redirect.fromFile("C:\\Users\\Raga\\Documents\\"+rollno+"\\input.txt"));
Process p = pb.start();
This question already has answers here:
Bitlocker script to unlock drive
(8 answers)
Closed 6 years ago.
I am trying to unlock a drive secured by bitlocker from Java. As far as I know there are no libs which can help me to handle that, so I was trying it through cmd. Here's the code:
public static boolean unlockDisk(String pwd) throws IOException
{
String[] script =
{
"manage-bde.exe", "-unlock", "D:", "-password",
};
Process process = new ProcessBuilder(script).start();
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
final OutputStream outputStream = process.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(pwd);
writer.newLine();
writer.close();
System.out.println("--------------------------------------");
System.out.println("Bitlocker log:");
String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
String tmp;
while ((tmp = stdError.readLine()) != null)
{
System.out.println(tmp);
}
System.out.println("--------------------------------------");
return true;
}
My Problem
If I execute this java code I get The handle is invalid with Code 0x80070006.
What I already tried
Different JDK Version 32 and 64 Bit Java 8 and Java 7 (JDK 32 complains somehow that it can't find the command manage-bde)
Different combinations of output streams, with and without newline...
Another script command for the processbuilder like "cmd.exe", "/k", "manage-bde.exe", "-unlock", "D:", "-password", or with /c instead of /k
With and without admin rights
Simple *.bat with the command manage-bde.exe -unlock D: -password (which works perfectly)
Locking the drive through a java command (which works perfectly)
The command without -password (which let's bitlocker claim that I have to define how I want to unlock the drive)
I googled around for some time and found others having this problems but in a different way with other applications. So it seems like a very common error message.
My guess
I think it has something to do with how I handle my Java output as Bitlocker input. Maybe I am using the wrong streams to write to.
I can't provide the value of the password within the script variable, because Bitlocker want doesn't accept that way of entering the password. Usually you enter manage-bde -unlock D: -password within the command line and after a few lines of output Bitlocker asks you for the password.
Well I described it as good as I can and hope that someone knows what the problem is.
Any suggestion, even if it just leads to a more precise error message, would be appreciated. If you have any questions, just let me know!
Thanks in advance!
I encountered same problem recently. I did a lot search. It seems that mange-bde.exe doesn't read user input from stdin. Someone said ssh client and telent clent running on Linux doesn't read password from stdin. Another example Linux command passwd. It has a flag called -stdin which enable the shell to read password from stdin. Therefore, I guessed manage-bde.exe may works in a similar way.
My solution is simulating keyboard input. The awt package can do the job.
This question already has answers here:
Run fortran exe in java
(3 answers)
Closed 8 years ago.
I have a Fortran exe. What I need to do.... I need to call that exe through java in Linux. After that it should ask for input file and output file.
This is my code:
Process process = new ProcessBuilder("/home/admin/Documents/file.out",
"input","output").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
It is running but nit asking for input and output file
To call external programms in java you need the java.lang.Runtime package. If you want a more convenient API have a look at Apache Commons Exec.
None of the code you have shown us "asks" anything.
I can see where you are passing two names (are they file names?) to your fortran program. But then it would be up to the fortran program to open those files and do something with them. If that's not happening, then the problem is in the fortran code ...
On the other hand, if your intention is to open the files in the Java code, and pass the file handles to the fortran program (as its standard input and standard output), then your code doesn't attempt to do that. You need to read the javadocs for ProcessBuilder. Pay attention to the stuff about redirecting input and output for the child process.
I'm trying to use Java to interface with a large batch file that uses psexec to execute commands on remote servers.
I'm able to launch the file using process builder and it works fine for most commands, but seems to be getting hung up.
One particular command from the batch file is as follows:
ECHO .
Echo Which would you like to reboot?
Echo 1-10. For computers, enter computer number.
Echo E. Exit
set /p userinp=choose a number(0-22):
but from Java I get:
.
Which would you like to reboot?
1-10. For computers, enter computer number.
E. Exit
and then it hangs
It's clearly not reading the set line, but more importantly I haven't yet figured out how to pass input back to the subprocess.
String[] command = {"cmd", "/c", "batchfile", "restart"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:\\"));
Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Any input would be appreciated.
Your batch job requires that you actually provide input in order to proceed, which is why it appears to 'hang'. You need to supply this input to the process, via its output stream. A highly simplified example:
PrintWriter writer = new PrintWriter(process.getOutputStream());
writer.println("10");
writer.flush();
Your process doesn't hang, it is just waiting for some input at the command line, before to proceed.
As you are reading the output from the process via Process.getInputStream(), you can send input back to it using Process.getOutputStream().
public abstract OutputStream getOutputStream()
Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.
Implementation note: It is a good idea for the output stream to be buffered.
Returns:
the output stream connected to the normal input of the subprocess.