This simple code has never worked for me in processing:
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("> prompt ");
str = in.readLine();
println(str);
}
}
catch (IOException e) {
}
Probably because the console output box cannot be used for input, unlike in Eclipse. Is there a simple workaround, or am I forced to do something like a dialog box (or keyPressed handling) for standard in?
If you are using the Processing IDE, Processing does not support this behavior natively. If you export your sketch and edit the java files, or use Eclipse, Proclipsing, core.jar, etc. you can access the System.in like any other java application, however, this would defeat the purpose of processing in that it doesn't typically run from the command line and is graphic in nature.
Best practice would be to capture the keystokes with the key pressed method. For example:
String str = "";
void keyPressed() {
str += key;
}
then in your draw() loop/method, you could handle the text input on str and clear it out if you wanted.
If you wanted something more sophisticated that would have a better UX, I suggest using something like ControlP5's TextField or TextArea.
Your program works perfectly (I named it test) and exported it as an Applet. I tested with cygwin as well as the windows command prompt:
$ cd test/applet
$ java -jar test.jar
Output (I typed "hello" and hit enter):
prompt> hello
hello
prompt>
I tried really quick on an Ubuntu terminal through ssh. I had issues getting it connected to the x11 server. Consider: http://en.wikipedia.org/wiki/Xvfb if that is an issue.
Just to confirm, I was able to run the SharedCanvasServer example included in Library->Network where I added a System.out.println to dump debug to the executing terminal.
java -cp "core.jar;net.jar;SharedCanvasServer.jar" SharedCanvasServer
Related
I have this program that I am writing that has this method that is supposed to execute a program but does not do anything. The method in question is as follows:
public void findCC_Data(List<String> l7) {
StringBuffer output = new StringBuffer();
Process p;
try {
for(String sql_file: l7) {
String command = "cleartool describe " + sql_file;
p = Runtime.getRuntime().exec(command);
System.out.println("Executing: " + command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
if (reader.readLine() == null) {
System.out.println("'reader.readLine()' is equal to null");
}
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(output.toString());
}
Does anyone know why the command does not do anything and the reader.readLine() method always returns null?
I am following a tutorial but using the cleartool program instead of the ping program basically. The tutorial is at this URL:https://www.mkyong.com/java/how-to-execute-shell-command-from-java/
Solution
I had the System.out.println(output.toString()) print statement outside of the for loop instead of inside it. Now when I move the SOP statement inside the loop it prints a million plus lines of information on ClearCase version control stuff. To fix put the SOP with the output.toString() inside the loop in the broken code above.
One possibility for a program in (java, python, bash, ...) to do nothing with ClearCase command is if said cleartool command is run within a dynamic view which has been set (cleartool setview).
As I explained before, the cleartool setview command opens a subshell in which commands are supposed to be run, which is not the case here (the java program runs in the main shell)
The other possible cause is that you are reading stdout, not stderr, and somehow this commands returns an error (maybe its execution path is not correct).
thought it would not matter anyway because a method I call before the one in question is supposed to change directories to the dynamic view. It appears it does not work as expected though because the result of the cleartool pwd command is just my desktop
Yes, each cleartool command operates in its own shell. You must set the right execution folder for each Java Process run("cleartool ...") commands, in order for those cleartool commands to start in the right folder.
See "execute file from defined directory with Runtime.getRuntime().exec", although the answer is a bit dated, and that might have changed with Java8.
As the OP noted, the output.toString() print statement was outside of the for loop instead of inside said loop.
You can see additional example in:
"Capturing stdout when calling Runtime.exec"
"No output from Runtime.getRuntime().exec(“ls”)"
Run your command inside a child shell using sh command and redirect the output to nohup, refer nohup and sh command.
once you have the command executed i.e. "nohup cleartool describe " + sql_file;
you can get the error or details from nohup.out file and confirm if there is an issue in executing the command.
I've created a GUI (swing) that executes a batch file that contains a command prompt .exe file execution with specific parameters.
When I run the batch file manually (by double clicking it), everything is as expected.
The problem is: the command prompt window doesn't open to show progress, moreover, it doesn't really start to work (only initiated) until I exit the GUI (forking?). When it starts to work, is works somewhere in the background and seen only in the task manager.
Only a blank command prompt window is opened.
From digging little bit around, I've constructed this command that gives me same result as above:
Runtime.getRuntime().exec("cmd.exe /c start \"Encoding\" cmd.exe /c start md \"" + Gui.outputDirField.getText() + "\\encoderOutput\" & cd \"" + Gui.outputDirField.getText() + "\\encoderOutput\" & \"" + Gui._batFile + "\" & pause");
Could you please assist?
Sorry if it sounds stupid..
this way works for me:
new Thread() {
#Override public void run() {
try {
Runtime.getRuntime().exec("cmd.exe /c start " + Gui._batFile);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}.run();
trashgod may be on to something. We ran into issues with paths with spaces. This is from the release notes for jre 7u21
Changes to Runtime.exec
On Windows platform, the decoding of command strings specified to Runtime.exec(String), Runtime.exec(String,String[]) and Runtime.exec(String,String[],File) methods, has been improved to follow the specification more closely. This may cause problems for applications that are using one or more of these methods with commands that contain spaces in the program name, or are invoking these methods with commands that are not quoted correctly.
For example, Runtime.getRuntime().exec("C:\\My Programs\\foo.exe bar") is an attempt to launch the program "C:\\My" with the arguments "Programs\\foo.exe" and "bar". This command is likely to fail with an exception to indicate "C:\My" cannot be found.
The example Runtime.getRuntime().exec("\"C:\\My Programs\\foo.exe\" bar") is an attempt to launch the program "\"C:\\My". This command will fail with an exception to indicate the program has an embedded quote.
Applications that need to launch programs with spaces in the program name should consider using the variants of Runtime.exec that allow the command and arguments to be specified in an array.
Alternatively, the preferred way to create operating systems processes since JDK 5.0 is using java.lang.ProcessBuilder. The ProcessBuilder class has a much more complete API for setting the environment, working directory and redirecting streams for the process.
Does your bat file requiere user interaction or why are you putting a pause on your command? If so, the Runtime.exec just runs the file with no window, why would you want a Window? >ou can get a Process object as a result from the exec, from this object you can get an InputStream (and if needed, an OutputStream) so you can print your output or interact with the process.
How can I set the focus (e.g. cmd+tab) of an arbitrary application (Java or not) from a Java program, on OSX?
Looking for an answer to this question, I came across this question, but it doesn't really help for OSX.
EDIT: one possibiltiy seems to be to use something like Quicksilver, and a Robot to send it keypresses with modifiers. I'd prefer something more portable, though, that requires less setup to make changes after it's compiled....
You should be able to reactivate an already running app using the open command that comes with OS X:
Runtime.exec("open /path/to/Whichever.app");
(Or some equivalent overload of that function.) This will also open an app if it's not running yet.
Chuck's answer tipped me off to osascript, so I decided to give it a shot straight from the command line. Managed to get it working with Runtime.exec(), osascript, and AppleScript.
Java launches an AppleScript and passes it the application name, using osascript from the command line, via Runtime.exec():
try {
List<String> shellCommandList = new ArrayList<String>();
shellCommandList.add("osascript");
shellCommandList.add("activateApplication.scpt");
shellCommandList.add(appName);
String[] shellCommand = (String[])shellCommandList.toArray(new String[0]);
Process p = Runtime.getRuntime().exec(shellCommand);
// if desired, pipe out the script's output
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String cmdOutStr = "";
while ((cmdOutStr = in.readLine()) != null) {
System.out.println(cmdOutStr);
}
// if desired, check the script's exit value
int exitValue = p.waitFor();
if (exitValue != 0) {
// TODO: error dialog
System.err.println("Invalid application name: "+ appName);
}
} catch (Exception e) {
e.printStackTrace();
}
And the AppleScript uses a run handler to capture the incoming argument:
on run (arguments)
set appName to (item 1 of arguments)
tell application appName to activate
return 0
end run
You can use the javax.script API to run AppleScripts. So you can write a script along the lines of "tell application "WhateverApp" to activate", filling in your arbitrary application for WhateverApp, and it should do what you want.
I am using the process class to run this command
/sdcard/file1.mpg /sdcar/file2.mpg > /sdcard/out.mpg
Here is how I am trying to do it:
Process processx = Runtime.getRuntime().exec(new String[] {"cat","/sdcard/file1.mpg /sdcard/file2.mpg > /sdcard/out.mpg" });
BufferedReader in = new BufferedReader(new InputStreamReader(processx.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// Waits for the command to finish.
processx.waitFor();
The command works from terminal but not when I try the above, can anyone see why?
Redirection (>) is not the OS feature. This is a feature of shell. To make it working from java you have to run something like the following:
/bin/sh yourcommand > yourfile
i.e. in your case:
/bin/sh cat /sdcard/file1.mpg /sdcard/file2.mpg > /sdcard/out.mpg
BUT could you please explain me why are you doeing this? Do you understand that this command is exact equivalent of cp /sdcard/file1.mpg /sdcard/file2.mpg /sdcard/out.mpg that can be coded in pure java without running any command line? Unless you have special reasons go on it! Write pure java code when it is possible. It is easier to debug, support and maintain.
There's absolutely no reason to use 'cat' to do this. It's not a supported or encouraged mechanism on Android, and there's no reason to launch a new executable to do what you can easily do in java code, by reading in one file and writing it out to the other.
For the record, you are trying to do a shell redirection, and that will not work since you are not executing a shell.
im using this small code to execute "cat" command and most of shell commands:
String[] cmdline = { "sh", "-c", "cat /sdcard/file1 >> /sdcard/file2" };
try {
Runtime.getRuntime().exec(cmdline);
} catch (Exception s) {
finishAffinity();
}
This is my first question on stackoverflow so I'll try to keep it concise and relevant.
I'm currently creating a Java program that is attempting to call an external program located on the system, in order to do this however I am required to call a shell script that sets up links to the relevant libraries to ensure that the system is linked to these before the external program can be executed.
The issue at hand is that I cannot invoke the shell script through Java, I've researched high and low and am aware that of alternative ways such as the use of the ProcessBuilder class. Unfortunately I'm quite new to the world of trying to invoke command line statements through Java and so I'm stuck for answers.
An example of the code I am using can be found below:
private void analyse_JButtonActionPerformed(java.awt.event.ActionEvent evt) {
// Get project path for copying of Fortran program to folder and execution
String projectPath = Newproject_GUI.getProjectPath();
String sourcePath [] = {"/bin/sh ", "-c ","source ~/set_env_WRF_gnu.sh"} ;
Runtime fortranAnalyser = Runtime.getRuntime();
try {
Process p = fortranAnalyser.exec("cp main.exe " + projectPath);
Process k = fortranAnalyser.exec(sourcePath);
BufferedReader is = new BufferedReader(new InputStreamReader(k.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(Analyser_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Process p works fine and does indeed copy main.exe to the intended directory when the method is called. Process k however does not and this is where the issue is.
Thanks in advance.
The issue is "source" is internal command of BASH (you are using "sh" but that is just BASH in the simplified mode). So what you do is:
you spawn new process "sh" and source something there (setting some VARIABLES I guess)
the process ends and all VARIABLES are lost
you spawn another process, but VARIABLES are already gone
I am not sure if you use those variables later on, but according to the script name it is probably setting some. Don't do that like this.
By the way if you only want to execute script in bash, you don't need to source it. To get it's side effects, just execute it with:
String sourcePath [] = {"/bin/sh ", "/home/XYZ/set_env_WRF_gnu.sh"} ;
Please note you cannot use ~ in this case, use Java to get your home dir.