Java Process get result - java

I am currently working on voice recognition project and I want to access certain keys based on user's voice commmand. For example If a user speaks 'a', I want to print a. I found a cmd command that does this work. This command works fine in command prompt and returns a as output. But i want to use this in my java application. I found a method that can fetch command output and prints it. But in this case it is not able to print 'a'. Please help..Here is the code snippet.
public void Voice() throws IOException {
Process p;
String work = "cmd /c nircmd.exe sendkey a press"; // used nircmd utility
p = Runtime.getRuntime().exec(work);
String output="";
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((output = reader.readLine()) !=null) {
System.out.println(output);
}
reader.close();
}

When you run Windows' command cmd from Java, keep in mind that your working directory is your project directory or the directory from where you run java. So from the symptoms you have described, it seems that when you run the nircmd utility from java, it is not found. Try giving a full path to the exe.
Replace
String work = "cmd /c nircmd.exe sendkey a press";
with
String work = "cmd /c "c:\\your-path\\nircmd.exe sendkey a press";

Related

Processbuilder: Cannot combine 2 paths as argument to execute app with a macro

So for work I would like to automate something for minitab. We get results from our microscope and these need to be put into Minitab. Now I wanted to make a program that does some changes to the text file and then automatically opens minitab with a macro. I have everything working except for the auto opening of the macro with minitab.
I can launch it from cmd manually no problem, so it should be working.
Code can be found below, after compiling and running I get this error
'C:/Program' is not recognized as an internal or external command,
operable program or batch file.
Process finished with exit code 0
Which makes me believe cmd does something like:
cmd.exe,/c,c:/Program,Files/..
instead of
cmd.exe,/c,c:/program files/...
String PathExe = "\"C:/Program Files/Minitab/Minitab 17/Minitab 17/Mtb.exe\"";
String Macro = "\"c:/minitAPP/Import.mtb\"";
ProcessBuilder builder;
builder = new ProcessBuilder("cmd.exe", "/c", PathExe + " " + Macro);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
There is no need to use cmd.exe to execute another .exe file. Just execute it directly, without the quotes:
ProcessBuilder builder = new ProcessBuilder(
"C:\\Program Files\\Minitab\\Minitab 17\\Minitab 17\\Mtb.exe",
"c:\\minitAPP\\Import.mtb");
By specifying an entire path as a single argument to ProcessBuilder, you ensure that the operating system will treat it as a single argument, which is the purpose of using quotations marks on a normal command line.

Get Windows Command Line charset in java

I've been having problems reading output of windows command line from Java, i'm using Runtime.getRuntime().exec()
I simplified my test case: I have a file called お読みください.txt, and i execute the following command cmd /c dir C:/PATH
Note: The actual command is tasklist, but it's the same result as long as i use Runtime.getRuntime().exec()
String[] cmd = new String[]{ "cmd", "/c", "dir" };
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput =
new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String s, result = "";
while ((s = stdInput.readLine()) != null) {
if (!s.isEmpty()) {
result += s + "\n";
}
}
System.out.println(result);
I just get ���ǂ݂�������.txt
I tried with no charset, default, and the other ones; after testing all charsets, i got the one i was looking for: Shift_JIS
And that must be because i have set Language for non-Unicode applications as Japanese. systeminfo.exe says ja;Japanese for Regional Config.
I can simply use Shift_JIS to read, but it will only work in my computer. What about other system configurations?
The question is, how can i get the correct charset to read Windows Console output?
Base on the answer of What encoding/code page is cmd.exe using?
You can execute cmd /k chcp && pause && exit to get current code page. Using Code Page Identifiers to find the mapping Java encoding name.

how to integrate Bash with Java

Can any body help me with how to compile a bash script as part of a java program. I am writing a simple java program that i want to use to invoke bash script commands.
my java code looks like the following:
try{
Process p = Runtime.getRuntime().exec("myscript.sh");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null){
System.out.println(line);
}
}
catch(IOException e){
System.out.println(e.getMessage());
}
and the "mysrcipt.sh" file is a simple script that contains the following lines
!/bin/bash
echo "enter your input followed by [ENTER]:"
read -e choice
echo $choice
My problem is, the program waits for an input at the read command in the script even if i enter multiple lines and press enter several times.
You can use:
Process p = Runtime.getRuntime().exec("bash_script.sh");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
// use bash script line output
}
It would be helpful to see some code showing what you're trying to accomplish.
Executing bash script in Java can be done using something like the following...
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("YOUR COMMAND STRING");
List<String> lines = IOUtils.readLines(process.getInputStream());
Runtime.exec() is what you need to execute your bash script, but be aware there are a few pitfalls. I found this to be a good article when starting to call external scripts.
It is written for a windows platform, but a lot of what is discussed is relevant to *nix as well.
See also this question.

How to code in java to run unix shell script which use rSync internally in windows environment using cygwin?

I am using cygwin to get unix environment on windows.
I have some shell script that run on cygwin to perform syncing works and other things. I want to executes these script through java code.
Also during executing of scripts on cygwin , certain information is displayed on terminal by using simple echo command.. I want to show all that information in my application.
How can I do this??
Use the Runtime class to run Cygwin. This is very brittle, and dependent upon your setup, but on my machine I would do:
Runtime r = Runtime.getRuntime();
Process p = r.exec("C:\\dev\\cygwin\\bin\\mintty.exe --exec /cygpath/to/foo.sh");
Then wait for the Process to complete, and get a handle to it's InputStream objects to see what was sent to stdout and stderror.
The first part of the command is to run cygwin, and the second is to execute some script, or command (using -e or --exec). I would test this command on the DOS prompt to see if it works first before cutting any code. Also, take a look at the options available by doing:
C:\dev\cygwin\bin\mintty.exe --help
Also from within the DOS prompt.
EDIT: The following works for me to print version information
public class RuntimeFun {
public static void main(String[] args) throws Exception {
Runtime r = Runtime.getRuntime();
Process p = r.exec("C:\\dev\\cygwin\\bin\\mintty.exe --version");
p.waitFor();
BufferedReader buf = new BufferedReader(
new InputStreamReader(
p.getInputStream()));
String line = buf.readLine();
while (line != null) {
System.out.println(line);
line = buf.readLine();
}
}
}
Unfortunately, can't seem to get it working with --exec, so you're going to have to do some more research there.
You can use something like this
String cmd = "ls -al";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
p.s. this doesn't handle errors

How to open the command prompt and insert commands using Java?

Is it possible to open the command prompt (and I guess any other terminal for other systems), and execute commands in the newly opened window?
Currently what I have is this:
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe","/c","start"});
I've tried adding the next command after the "start", I've tried running another rt.exec containing my command, but I can't find a way to make it work.
If it matters, I'm trying to run a command similar to this:
java -flag -flag -cp terminal-based-program.jar
EDIT Unfortunately I have had some strange findings. I've been able to successfully launch the command prompt and pass a command using this:
rt.exec("cmd.exe /c start command");
However, it only seems to work with one command. Because, if I try to use the command separator like this, "cmd.exe /c start command&command2", the second command is passed through the background (the way it would if I just used rt.exec("command2");). Now the problem here is, I realized that I need to change the directory the command prompt is running in, because if I just use the full path to the jar file, the jar file incorrectly reads the data from the command prompt's active directory, not the jar's directory which contains its resources.
I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.
rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");
If you are running two commands at once just to change the directory the command prompt runs in, there is an overload for the Runtime.exec method that lets you specify the current working directory. Like,
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start command", null, new File(newDir));
This will open command prompt in the directory at newDir. I think your solution works as well, but this keeps your command string or array a little cleaner.
There is an overload for having the command as a string and having the command as a String array.
You may find it even easier, though, to use the ProcessBuilder, which has a directory method to set your current working directory.
Hope this helps.
public static void main(String[] args) {
try {
String ss = null;
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
BufferedWriter writeer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writeer.write("dir");
writeer.flush();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((ss = stdInput.readLine()) != null) {
System.out.println(ss);
}
System.out.println("Here is the standard error of the command (if any):\n");
while ((ss = stdError.readLine()) != null) {
System.out.println(ss);
}
} catch (IOException e) {
System.out.println("FROM CATCH" + e.toString());
}
}
The following works for me on Snow Leopard:
Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);
Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,
Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Allows you to read the line-by-line output of the command pretty easily.
The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:
{"start", "cmd.exe", "\c"}
To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.
You just need to append your command after start in the string that you are passing.
String command = "cmd.exe /c start "+"*your command*";
Process child = Runtime.getRuntime().exec(command);
String[] command = {"cmd.exe" , "/c", "start" , "cmd.exe" , "/k" , "\" dir && ipconfig
\"" };
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("D:\\Folder1"));
Process process = probuilder.start();
You can use any on process for dynamic path on command prompt
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\rakhee\\Obligation Extractions\" && dir");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\oxyzen-workspace\\BrightleafDesktop\\Obligation Extractions\" && dir");
Please, place your command in a parameter like the mentioned below.
Runtime.getRuntime().exec("cmd.exe /c start cmd /k \" parameter \"");
You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.
1) to combine 2 commands use (for example pause and ipconfig)
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());
2) to show the content of a file use (MORE is a command line viewer on Windows)
File selectedFile = new File(pathToFile):
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());
One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.

Categories