Java String execution in Linux terminal - java

I am using StringBuilder to create a string and then trying to execute the string on Linux terminal. But instead of executing whole command, it executed half command and then terminates it. This is my java code snippet:
moteCommand.append("CFLAGS+=-DCC2420_DEF_CHANNEL=1");
moteCommand.append(" ");
moteCommand.append("make telosb install.");
moteCommand.append(moteIdList.get(i).toString());
moteCommand.append(" bsl,");
moteCommand.append(moteAddrList.get(i).toString());
String moteCommand2 = moteCommand.toString();
Process moteProgProcess = Runtime.getRuntime().exec(moteCommand2, null,"/opt/tinyos-2.x/apps/XXX/);
It gives me this error:
Cannot run program "CFLAGS+=-DCC2420_DEF_CHANNEL=1" (in directory "/opt/tinyos-2.x/apps/xxx"): java.io.IOException: error=2, No such file or directory
I don't understand why system process is trying to execute only half of the string. Please let me know if anybody knows the reason.
Thanks.

When you call Runtime.exec(), the characters up to the first space must be the name of the program you want to launch. After that, each "part" between spaces is a separate argument. Note that calling Runtime.exec() is completely different from typing a command in bash (or any other shell...) and pressing enter!! If you type a command that works fine in bash, it doesn't mean it will work with Runtime.exec(). For example, shell commands (which are not external programs) won't work in Runtime.exec().
What you should do is use ProcessBuilder.
Instantiate it, manipulate its Map that represents the environment options (ie, the things you are passing before the command name, such as the cflags, and anything else you might want), set the command name, give the arguments one at a time (the arguments won't get split at spaces, so you can pass paths containing spaces, for instance), etc. You can manipulate the stdin, stdout and stderr in many different ways (such as: use the same as those used by the Java process; or get instances of InputStream and OutputStream to write to and read from the process; or pipe them), and run the process.
Something along the lines:
final ProcessBuilder pb = new ProcessBuilder("make", "telosb", "install" blablablabla);
final Map<String, String> env = pb.environment();
env.put("CFLAGS", "....your options....");
pb.start(); // take the Process instance, and you will be able to read the output, wait for it to finish, get the exit code, etc

Related

How to run multiple CMDs with quotes in one terminal in java

I need to execute in java 2 commands in one terminal,
each command contains a path with spaces.
For example:
CMD 1: "C:\user\with space\bat1.bat"
CMD 2: "C:\user\with space\bat2.bat"
The purpose is running CMD 2 only if CMD 1 ran successfully, in the same terminal.
I've tried to use && :
Runtime.getRuntime().exec("\"C:\\user\\with space\\bat1.bat\" && \"C:\\user\\with space\\bat2.bat\"");
But I got the following error:
'\"C:\user\with space\bat1.bat\"' is not recognized as an internal or external command,
operable program or batch file.
How can I run them both and make it recognize each command separately?
You've confused a terminal with execute. These are not the same thing. Your OS can run applications. The terminal isn't "the OS". It's an application. When you type stuff in there, you are not sending it 'to the system', you're just typing in that application. No different from me typing in this very text box in a web browser. I type a letter and it appears. I hit enter and stuff happens.
The shell does a whole boatload of 'parsing' on what you type and then uses the equivalent of Runtime.getRuntime().exec in the language it is written in.
There are a lot of things that /bin/bash, /bin/zsh, /bin/fish, windows's cmd.exe, and all those other shells do. For some of these, it really IS the OS that does it... depending on which OS you're using. It's best to rely on absolutely none of these:
Scour the PATH when you type a non-absolute-path executable to know which one to run.2
Append .exe, .bat, .com, or similar.
A whole bunch of well known commands like cd, ls, mkdir, etcetera.
&&, || and other ways to chain things.
filename substitutions, such as whatever.exe *.txt (the *.txt is 'substitution').1, same goes for ?.
variable substitution, such as /bin/foo $fn.
Redirect pipes such as 2>/dev/null or <myfile.txt.
splitting the command up by separating on spaces and considering the first thing the path of a command and all other things, each individually, a single argument... but then looking at quotes, using those to figure out certain spaces are not separators between parameters, and removing the actual quote characters of course.
Replace ~ with the user's home dir.
And much, much more.
You need to do all of it yourself. That's why you should never use Runtime.getRuntime().exec and always use ProcessBuilder instead. You can set up redirects with that, do the argument splitting on your own. Always specify an absolute path. Don't use * or ? for anything, etcetera.
You can't write, from within java, a magical way to make 2 batch files not open up 2 black boxes. Instead, create a new batch file that runs both batch files (I think you have to do CALL bat1.bat to avoid 3 black boxes showing up), and then run that, and you can't just run the batch file, you run cmd.exe and tell IT to run the batch file. If it's very very simple, you may be able to tell CMD to do it in one go.
Path workingDir = Paths.get(".");
List<String> batOfBatsContent = List.of(
"#ECHO OFF",
"CALL bat1.bat || GOTO :fail",
"CALL bat2.bat",
":fail");
Path megaBat = workingDir.resolve("doEverything.bat");
Files.write(megaBat, batOfBats.stream().collect(Collectors.joining("\r\n"));
ProcessBuilder pb = new ProcessBuilder();
pb.command(System.getenv("COMSPEC"), "/c", batOfBats.getAbsolutePath());
pb.start();
Or possibly:
Path workingDir = Paths.get(".");
ProcessBuilder pb = new ProcessBuilder();
pb.command(System.getenv("COMSPEC"), "/c",
"\"" +
workingDir.resolve("bat1.bat").getAbsolutePath() +
"\"&&\"" +
workingDir.resolve("bat2.bat").getAbsolutePath()
+ "\"");
pb.start();
[1] Actually, windows does do this, probably. Posix OSes (everything that isn't windows, at this point in time) definitely don't.
[2] Java tries to do this, sort of, but it's not particularly reliably. If you don't have to rely on it, don't. It's security-wise dubious in any case to do so.

Is it possible to have a Java program communicate with terminal?

I know you can use terminal/cmd to pass in arguments to a Java program, but can you do it the other way, ie have a Java program pass info back to terminal?
More specfically I want to do something like this:
use terminal to launch and pass in value to a Java program
do stuff based on input and pass back a value
use that value to encrypt a file using terminal
repeat
To get your started:
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. - Java API
You can basically run anything in terminal using this class:
Process p = Runtime.getRuntime().exec(command, null);
Where command is like ffmpeg -help, for example.
The sort of equivalent of args passed to program in the start of main method is an Integer passed to program exit statement, being the return value of the program:
System.exit(0);
This number can be any Integer.
If you run your program by java yourProgram, you can get exit code by
echo $?

Redirecting the input from file with multiple Scanner objects for Stdin

I am current using a small command line interface for one of our tools.
I would like to to provided input from a file or bash script file to automate the input.
Problem is the CLI uses multiple Scanner object to read input from stdin. There is not a problem inherently when manually inserting input since only one Scanner object is used at any given time, but when stdin in redirected, seems the buffer is attached to the first Scanner object which is only used for the first value read and I receive the java.util.NoSuchElementException.
Just to add, my conclusion on the issue is based on this:
Error while redirecting the input from file
Is there any bash magic I can use to redirect stdin in this case? Or maybe even JVM args to assist?
View Reddit Answer
The main idea to this solution would be to have delayed input passed into the script automatically. When the second Scanner object is created, then the expected input should be pushed into standard in, thus getting around the issue of the entire input being caught in only the first scanner.
So instead of having a text file with simple input values, would could have shell script that sleep between each input value.
#!/bin/sh
echo 3
sleep 1
echo 4
And then running the final program as follows:
./delayedEchoScript | java -jar myProgram.jar

How do you pipe the output of one file to input of another in Java?

Can someone show me code of something simple that pipes the output from one java file to the input of another in Java?
Say you have a file that is called hello.java that just simply outputs "hello". How would I pipe this output from the command line into another Java program called addWorld.java that simply adds "world" to the end of the input from hello.java and then outputs "hello world" on the console screen?
I'm sure it is very simple, but I've looked around and I still don't understand how to do it. I've tried to make an example that is as simple as possible so there isn't a lot of code written so I can just understand what to do in a general case. Thanks.
You'll want to start the second java program using run time probably and add the output for the first command as a parameter for running the second, as from what I've tried Windows does not like piping into other programs.
Quick how-to: https://stackoverflow.com/a/8496537/3342157
Information on Runtime: http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
On Windows, in the command line, this is done with the redirection operator (>)
It is done as so:
java hello > java addWorld
This would take the stdout of hello.java (anything printed using System.out) into the stdin of addWorld.java as a command line argument (the args part of public static void main(String[] args))
EDIT:
The pipe character (|) filters the stdout of the program through a program. If sort sorts a program alphabetically based on its stdin, typing this:
simon-answers.txt | sort > simon-answers-sorted.txt
into a windows command prompt would take the lines in simon-answers.txt ("Simon says" commands) and pipe (|) them through sort and then redirect (>) them to the text file simon-answers-sorted.txt

Java exec on Unix

I have the Java code below running on Unix (both AIX and Linux), but it doesn't work. If I run this code the file q1.01 is not compressed, and I don't get any exceptions thrown (The file q1.01 exists, and I expect to find the file q1.01.Z after the command runs.) At the command prompt if I type "which compress" it reports back with "/usr/bin/compress". If I type the command "/usr/bin/compress q1.01" at the Unix prompt it works fine. Any ideas on what might be wrong?
String cmd = "/usr/bin/compress q1.01";
Runtime.getRuntime().exec(cmd);
[Later edit: the problem was in the initial description; the OP was passing a wildcard and not q.01. So my answer below is wrong, except for the part in bold. I'm leaving it so the comments after it will make sense.]
It's trying to run /usr/bin/compress as the program name without arguments.
There are many forms of the Runtime.exec() method. You're using the .exec(String) version, which just takes the executable. Instead, you need to use the .exec(String[]) array version, which takes the executable in String[0] and the parameters in String[1..].
.exec() wants a String array for passing arguments.
Try
String[] cmd = new String[] { "/usr/bin/compress", "q1.01" };
Runtime.getRuntime().exec(cmd);
Note that .exec does not call the local command shell. That means we have to do, among other things, wildcard expansion and even some argument parsing before calling .exec(). This is why you can't just pass it your full command line.
There were a couple of problems. One was that I had tried using wildcards, and since the shell isn't invoked they weren't being expanded. The other problem was that I had created very small test files like this: "echo 'abc' >q1.01". This file was so small that compress couldn't compress it any further and so left it alone. (Stupidly, I think when I typed in the command at the shell I used a different filename, which did compress.)
Thanks everyone for the answers. It did help!
You probably need to use an absolute path to the file. Capture the output though, to see what the problem is - see this page for info on how to do that.
This site may be able to provide some clues.
If the process input stream is null, I suspect that Java wasn't even able to spawn the subprocess. What does Process#exitValue() return?
I'd recommend using strace to see what actually happens on the system-call level. The actual exec() arguments and return code would be especially interesting to see.

Categories

Resources