Меню Рубрики

Linux runtime getruntime exec

How to run Linux commands in Java?

I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.

Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.

9 Answers 9

You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here’s a complete program that will showcase how to do it:

When compiled and run, it outputs:

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it’s input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder .

Источник

Use keytool with Runtime.getRuntime().exec() under Linux

I’d like to create a self-signed certificate by invoking keytool in my java script. Here is a simplified version of my code which includes the problem I have:

There is no error when I ran it. But it did not give me the keystore. My questions are:

The certificate generated by keytool is not considered as the «subprocess’s output» which needs to be fed to the parent process using getinputstream() , is it?

If it is, I also tried the getinputstream() thing as discussed in the following post,

the program just got stuck and seems to never stop.

  1. Is there any other ways to create self-signed certificate using java program?

I am a newbie in Java and English is not my first language. I hope I have expressed my question clearly.

1 Answer 1

You could try a different approach again — since keytool is written in Java and it is delivered with the JDK, you can actually instantiate the keytool class directly, like in this answer. This approach will let you generate a self-signed certificate in the JKS file of your choice, but it won’t give you programmatic access to the generated certificate.

Источник

Java Runtime.getRuntime().exec for unix find command with not path

tried multiple ways. Command to delete files under a set of directories except one specific subdirectory works fine when commmand run on Linux.

Same command when run via Java exec doesn’t seem to recognize the path and everything gets wiped out.

tried escpace character \ before the («) double quotes nothing seems to help.

any thoughts, please help.

i get the command line string from a database lookup where i have the entire find command

I added a sysout(commandline) right before the

and i see the command in the stdout file on the server. It looks good, when i run that command on the server it works fine.

1 Answer 1

Runtime.exec(String) claims another victim!

Never use this function. It has exactly zero valid use cases. Use the Runtime.exec(String[]) version instead, or (even better) ProcessBuilder .

Both have two commonly used idioms. The first emulates C’s simple and sloppy system by running the command in a shell:

and a secure and robust version closer to C’s execv(char*, char**) :

The first just requires you to know how to use a shell. The second requires you to additionally know how a shell works behind the scenes, and can not be blindly copied based on this example.

Источник

Java Runtime.getRuntime(): getting output from executing a command line program

I’m using the runtime to run command prompt commands from my Java program. However, I’m not aware of how I can get the output the command returns.

I tried doing System.out.println(proc); but that did not return anything. The execution of that command should return two numbers separated by a semicolon. How could I get this in a variable to print out?

Here is the code I’m using now:

But I’m not getting anything as my output, but when I run that command myself it works fine.

12 Answers 12

Here is the way to go:

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

A quicker way is this:

Which is basically a condensed version of this:

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

If use are already have Apache commons-io available on the classpath, you may use:

Besides using ProcessBuilder as suggested Senthil, be sure to read and implement all the recommendations of When Runtime.exec() won’t.

Also we can use streams for obtain command output:

@Senthil and @Arend answer (https://stackoverflow.com/a/5711150/2268559) mentioned ProcessBuilder . Here is the example using ProcessBuilder with specifying environment variables and working folder for the command:

At the time of this writing, all other answers that include code may result in deadlocks.

Processes have a limited buffer for stdout and stderr output. If you don’t listen to them concurrently, one of them will fill up while you are trying reading the other. For example, you could be waiting to read from stdout while the process is waiting to write to stderr . You cannot read from the stdout buffer because it is empty and the process cannot write to the stderr buffer because it is full. You are each waiting on each other forever.

Here is a possible way to read the output of a process without a risk of deadlocks:

Источник

Java Process cannot get the InputStream through Runtime.getRunTime().exec()

The Code has issues with getting the InputStream from the Process, because if I run the Shell script from my Terminal it runs completely fine, but if I Run the Script like this,the str is always null,

I am using this code to get the output of the Shell Script directly into Java instead writing the Script Output in the File

Is there any other way to achieve this,or how can I get the issue solved using the current approach

5 Answers 5

I think something returned through the error stream, so you can try to check something from the Process.getErrorStream().

You should also wait for the created process to prevent your main program completes before it. Use Process.waitFor();

Edit you /home/abhishek/workspace/Pro/run if it is a shell and add the following line on top.

and give required execute permissions to /home/abhishek/workspace/Pro/run .

Then use the following line

Now if the run program prints anything you should see it in the output.

Your code looks fine. So, I believe that problem is either in command line you are using ( bash /home/abhishek/workspace/Pro/run ) or in your script itself.

I’d suggest you to perform the following steps:

  1. try to run some well-known command instead of your script. For example pwd . Check that your code that is reading from input stream works correctly.
  2. Now try to simplify your script. Create script run1 that just runs the same pwd . Now run this script from java and see that it is working. BTW you do not have to run it as bash yourscript . You can directly run it without bash prefix
  3. If all this works start to move from simple to your real script step-by-step. I believe you will find your mistake. Probably your script cannot start for some environment related problems.

Possible problem is by the time you obtain inputStram the sub-process is not ready

Источник

How to tell Java run this Runtime.getRuntime().exec, without waiting what ever command it has to run, simply run it in backend?

How to let the Runtime.getRuntime().exec(p) run without waiting for the sleep 10?? Currently its wrong, its waiting until the exec gets complete and then moves to next. Where i need to on the fly let the exec running so that after 10 second later it can kill the PresentationInProjector.jpg.

3 Answers 3

According to the docs exec() :

Executes the specified string command in a separate process.

So any call to exec() should not block unless you used waitFor() on the returned process of the Runtime .

Here is a small example(Exception handling omitted):

exec() is not making thread wait until spawned process ends by default. You need to call process.waitFor() explicitly to make current process wait. I guess that PlayThisSlideShow(«PresentationInProjector.jpg»); is being called immediately after exec() . What you see is system making JVM process be running as long as child process is running. I guess there is no way to overcome this easily, to have parent process killed while child process still running.

Why can’t you kill presentation projector from Java?

will not do what you expect. Runtime.exec is not a shell and doesn’t understand things like () grouping, ; or | . But the actions you’re trying to perform can be done purely in Java, you don’t need to exec an external process. For example (exception handling omitted):

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.9.18.37632

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Simcity buildit mac os
  • Sim city mac os
  • Silver efex pro mac os
  • Silent hunter для mac os
  • Signal private messenger mac os