Runtime.getRuntime().exec could not execute/show Tabtip.exe - java

I've set this OnClick method in JavaFX SceneBuilder on a text field that will pop up the Windows 8 touch keyboard if the user select the textfield. However it seems to be nothing happen when I click on the textfield but when I try to check Tabtip.exe in the task manager, it did shown up there. The codes are:
try
{
Runtime rt = Runtime.getRtuntime();
rt.exec( "cmd /c C:\\Programs Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe");
}
catch
{
ex.printStackTrace();
}
There is not errors triggered or whatsoever, and TabTip.exe is running in task manager, but the pop up keyboard does not show up, anyone has any solution to this? Thanks!

Whenever you want to execute a command which contains spaces in command prompt, you have to wrap it in double quotes.
Like this:
String commandStr = "cmd /c \"C:\\Program Files\\Common Files\\Microsoft Shared\\ink\\mip.exe\"";
rt.exec( commandStr );
And In addition to that, if you want to know your errors, you can get error stream from object of class Process which is returned by runtimeObject.exec().
String commandStr = "cmd /c C:\\Programs Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe"; // Like you did
InputStream is = rt.exec( commandStr ).getErrorStream();
int b;
while((b=(is.read()))!=-1)
System.out.print((char)b);
}

Please do like this. For me it is ok in window10 with javaFx application.
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "\"C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe");
builder.redirectErrorStream(true);
Process p;
try
{
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);
}
}
catch (IOException e)`enter code here`
{
// TODO Auto-generated catch block
e.printStackTrace();
}`enter code here`

The only way to run the TabTip.exe is to run the software on Admin mode.
I found the following batch code on the internet.
How to Use On-Screen and Touch Keyboard Instead of Spiral Keyboard
tasklist | find /I "TabTip.exe" >NUL && (taskkill /IM "TabTip.exe" /T)
start "" "TabTip.exe"
That code kills the TabTip process and executes a new TabTip.
In my case, I created a file called keyboard.bat and added the previous example.
In java, I created a method in order to read this file in the same folder.
That is my code
try{
File file = new File("keyboard.bat");
Runtime.getRuntime().exec(file.getAbsolutePath());
}catch(IOException ex){
Logger.getLogger(RunGazePoint.class.getName()).log(Level.SEVERE, null, ex);
}
after that, I compile my app and wrap it in executable mode with launch4j software.
Another way Is to execute by command, If you are using a multithreaded the system can avoid the lecture of file and not execute the software.
create two methods in order to kill and call the keyboard.
//hide the Keyboard
String[] array = new String[]{"cmd.exe","/c","taskkill /IM \"TabTip.exe\" /F\n" +
""};
Runtime.getRuntime().exec(array);
//Show the keyboard
String[] array = new String[]{"cmd.exe","/c","start \"\" \"TabTip.exe\""};
Runtime.getRuntime().exec(array);

Related

Using ADB pull command in a Java program

I can't get the ADB command to work in Java. The adb command works when inputting it directly to the command line. But when running it in Java, I get error
Cannot run program "adb -s shell": CreateProcess error=2,file not found
What is the proper syntax for running Windows Command line from Java?
The adb command "adb devices" works in the Java application. The command I'm trying to run is "adb pull sdcard/Download/symmetri.txt C:/Users/myUsername/Downloads/Sources", which works in the command prompt, but not from within the Java application. My code is:
public void FilePush() {
try{
String androidFilePath = "sdcard/Download/symmetri.txt ";
String windowsFilePath = "C:\\Users\\myUsername\\Downloads\\Sources\"";
List<String> cmd = new LinkedList<>();
cmd.add("adb -s shell");
cmd.add("adb");
cmd.add("pull");
cmd.add(androidFilePath);
cmd.add(windowsFilePath);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream(true);
Process p = builder.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
I also tried without adb -s shell" and with
String androidFilePath = "\"/storage/sdcard0/Download/symmetri.txt\"";
String windowsFilePath = "\"C:\\Users\\myUsername\\Downloads\\Sources\\"";
But got the same error
Remove the line
cmd.add("adb -s shell");
as you don't want shell but pull.
Thx to the helpful people here, I finally got it to work! I first needed to run adb.exe as a command, before I could run any adb commands. I needed to remove ("adb -s shell") from my list of commands. I was trying to acces a file in the external storage instead of the internal one which needs root access
(Although I have no clue why I can acces the exact same file in a Command prompt window without permitting root acces). If you want to access external files, add root access with
adb root
Full code that works for anyone who might face the same issue :
public void FilePush() {
try{
String androidFilePath = "/storage/emulated/0/Android/data/com.example.myapp/files/myfile.txt";
String windowsFilePath = "C:\\Users\\myUsername\\Downloads\\Sources";
List<String> cmd = new LinkedList<>();
cmd.add("C:\\Users\\myUsername\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe");
cmd.add("pull");
cmd.add(androidFilePath);
cmd.add(windowsFilePath);
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
String line = "null";
pb.redirectErrorStream(true); // can use these 2 line if you want to see output or errors in file.
pb.redirectOutput(new File("C:\\Users\\myUsername\\Downloads\\Sources\\logs.txt"));
Process p = pb.start();
while(p == null)
Thread.sleep(1000);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-]+)(\\s+)(device)");
Matcher matcher;
while ((line = in.readLine()) != null) {
if (line.matches(pattern.pattern())) {
matcher = pattern.matcher(line);
if (matcher.find()) ;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}

How do I run GDB and accept GDB commands through Java output console?

I am trying to build a GUI for GCC which has some basic functionalities like compile, link, execute, debug, etc for C++ programs using Java. I am creating strings of command which I pass to the ProcessBuilder and run it via command prompt and GCC.
command = "cd src & cd Resources & g++ " + compileFile.cpp +" -Wall "+ " -o "+ "tempOut";
This is a sample code for compiling the file.
Part of this is the debug functionality for which I am using GDB. Now the problem is GDB needs additional input to add breakpoints, remove breakpoints and so on. I am having trouble on how to pass these necessary inputs to GDB via Java terminal. If I pass the commands in the command prompt, it is working fine and I get the desired output.
enter image description here
But whenever I fire the GDB command from the Java program, I cannot pass any inputs from the IDE's terminal. I am aware that each GDB command uses a different process and I tried attaching Java's process ID to GDB but I just get a blank output console. It seems that the GDB session has started but there is no way to interact with that process through the IDE's output console.
int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("#")[0]);
command = "gdb attach "+ pid;
fireCommand();
EDIT
This is the method that interacts with command prompt to take input and display output in the IDE's output console:
public void fireCommand() {
String line;
String os = System.getProperty("os.name");
ProcessBuilder builder;
if(os.startsWith("Win")) {
builder = new ProcessBuilder("cmd.exe", "/c", command);
}
else{
builder = new ProcessBuilder("bash", "-c", command);
}
try {
process = builder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while ((line = reader.readLine()) != null) {
if(line.contains("Input the value")) {
//any other user input in non debug execution
String value = JOptionPane.showInputDialog(line);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream()));
writer.write(value, 0, value.length());
writer.newLine();
writer.close();
}
else {
output.append(line).append("\n");
}
}
int exitVal = process.waitFor();
if (exitVal == 0) {
//display("Success!");
display(output.toString());
} else {
String lineErr;
BufferedReader readerErr = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while ((lineErr = readerErr.readLine()) != null) {
outputErr.append(lineErr).append("\n");
}
//display(exitVal);
display(outputErr.toString()); //Display the uncatched errors
}
} catch (IOException e) {
display("There was a problem with the I/O");
e.printStackTrace();
} catch (InterruptedException e) {
display("There was a interruption with the execution");
e.printStackTrace();
}
if(!outputErr.toString().isEmpty())
errorFormatDisplay(); //display Error output function
}
Any leads on this would be very helpful. Thank you.
I am aware that each GDB command uses a different process
No, gdb runs as one process. Did you mean to say that you are creating a new gdb process every time you try to pass it a gdb command ?
It seems that the GDB session has started but there is no way to interact with that process through the IDE's output console.
Maybe you should use The GDB/MI Interface, which e.g. the Emacs debugger mode gud uses.

Execute commands in CMD on Windows with Java code

I want to write a Java code that would perform commands in Windows CMD.
I looked through the site and found out how to send and work with single request. For example create new Process and in execute ("cmd /c dir") then using input stream I can get the answer that is displayed.
How to open the process of cmd and let the user to enter cmd commands?
For example, I open application and it directly opens cmd process, then user can type "dir" and get the output.
After type "cd ../../"
and after type "dir" again and get the output with new path containment.
If it can be performed then how to do it? Or in order to perform this need to open each time a new process and execute ("cmd /c some_reqests")?
Nice question, you can in fact call cmd as a new process and use standard input and standard output to process data.
The tricky part is knowing when the stream from a command has ended.
To do so I used a string echoed right after the command (dir && echo _end_).
In practice I think it would be better to simply start a process for each task.
public class RunCMD {
public static void main(String[] args) {
try {
Process exec = Runtime.getRuntime().exec("cmd");
OutputStream outputStream = exec.getOutputStream();
InputStream inputStream = exec.getInputStream();
PrintStream printStream = new PrintStream(outputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
printStream.println("chcp 65001");
printStream.flush();
printStream.println("dir && echo _end_");
printStream.flush();
for(String line=reader.readLine();line!=null;line=reader.readLine()){
System.out.println(line);
if(line.equals("_end_")){
break;
}
}
printStream.println("exit");
printStream.flush();
for(String line=reader.readLine();line!=null;line=reader.readLine()){
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try this
Process p = Runtime.getRuntime().exec("ps -ef");
found it at http://alvinalexander.com/java/edu/pj/pj010016

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.

how to launch a shell script in a new gnome terminal, from a java program

I'm trying to run a shell script (say myscript.sh) from a java program.
when i run the script from terminal, like this :
./myscript.sh
it works fine.
But when i call it from the java program, with the following code :
try
{
ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
It doesnt goes the same way.
Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.
Question : Is there some way to launch this script in a new terminal using java.
PS : i've found that "gnome-terminal" command launches a new terminal in shell,
But, i'm unable to figure out, how to use the same in a java code.
i'm quite new to using shell scripting. Please help
Thanks in advance
In java:
import java.lang.Runtime;
class CLI {
public static void main(String args[]) {
String command[] = {"/bin/sh", "-c",
"gnome-terminal --execute ./myscript.sh"};
Runtime rt = Runtime.getRuntime();
try {
rt.exec(command);
} catch(Exception ex) {
// handle ex
}
}
}
And the contents of the script are:
#!/bin/bash
echo 'hello!'
bash
Notes:
You'll do this in a background thread or a worker
The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
The shell script is located in the same path as the calling Java class.
Don't overrwrite your entire PATH...
pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.
Try this instead
pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));
Or, use the full directories to your commands in your script file.
You must set your shell script file as executable first and then add the below code,
shellScriptFile.setExecutable(true);
//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("Shell script executed properly");
}
This worked for me on Ubuntu and Java 8
Process pr =new ProcessBuilder("gnome-terminal", "-e",
"./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();
The previous code creates a new terminal in a specificied directory and executes a command
script.sh Must have executable permissions
public class ShellFileInNewTerminalFromJava {
public static void main(String[] arg) {
try{
Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
}catch(Exception e){
e.printStackTrace();
}
}
}

Categories