Java выполнить команду linux

Running Bash commands in Java

See also When Runtime.exec() won’t for many good tips on creating and handling a process correctly. Then ignore it refers to exec and use a ProcessBuilder to create the process.

Hello. I tried to use your class to execute Bash- Commands in my Java application, but when I run the command «cat» it returns null.

8 Answers 8

You start a new process with Runtime.exec(command) . Each process has a working directory. This is normally the directory in which the parent process was started, but you can change the directory in which your process is started.

ProcessBuilder pb = new ProcessBuilder("ls"); pb.inheritIO(); pb.directory(new File("bin")); pb.start(); 

If you want to run multiple commands in a shell it would be better to create a temporary shell script and run this.

public void executeCommands() throws IOException < File tempScript = createTempScript(); try < ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString()); pb.inheritIO(); Process process = pb.start(); process.waitFor(); >finally < tempScript.delete(); >> public File createTempScript() throws IOException < File tempScript = File.createTempFile("script", null); Writer streamWriter = new OutputStreamWriter(new FileOutputStream( tempScript)); PrintWriter printWriter = new PrintWriter(streamWriter); printWriter.println("#!/bin/bash"); printWriter.println("cd bin"); printWriter.println("ls"); printWriter.close(); return tempScript; >

Of course you can also use any other script on your system. Generating a script at runtime makes sometimes sense, e.g. if the commands that are executed have to change. But you should first try to create one script that you can call with arguments instead of generating it dynamically at runtime.

It might also be reasonable to use a template engine like velocity if the script generation is complex.

You should also consider to hide the complexity of the process builder behind a simple interface.

Separate what you need (the interface) from how it is done (the implementation).

public interface FileUtils

You can then provide implementations that use the process builder or maybe native methods to do the job and you can provide different implementations for different environments like linux or windows.

Finally such an interface is also easier to mock in unit tests.

Источник

How do i run a Linux terminal cmd from a java program [duplicate]

I am trying to call my rrdtool cmd from a java class, not sure how to go about it. I have tested my RRDTool cmd from my terminal and it is successful, see below.

rrdtool update mydb.rrd 1385056701:6:5 

6 Answers 6

You can use the below command format to run your Linux command.

Runtime r = Runtime.getRuntime(); Process p = r.exec(yourcmd); 

Hope you get your answers here.

 public class ShellTest < public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException < // Get runtime java.lang.Runtime rt = java.lang.Runtime.getRuntime(); // Start a new process: UNIX command ls java.lang.Process p = rt.exec("ls"); // Show exit code of process System.out.println("Process exited with code http://blog.art-of-coding.eu/executing-operating-system-commands-from-java/" rel="nofollow">also check here for more details

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Nov 21, 2013 at 18:15
Add a comment |
0

Try like this(As answered by paxdiablo):

public static void main(String args[]) < String s; Process p; try < p = Runtime.getRuntime().exec("ls -aF"); BufferedReader br = new BufferedReader( new InputStreamReader(p.getInputStream())); while ((s = br.readLine()) != null) System.out.println("line: " + s); p.waitFor(); System.out.println ("exit: " + p.exitValue()); p.destroy(); >catch (Exception e) <> > 

Also check java.lang.Runtime.exec for details.

Executes the specified string command in a separate process.

This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).

Источник

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.

10 Answers 10

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:

import java.io.BufferedReader; import java.io.InputStreamReader; public class testprog < public static void main(String args[]) < String s; Process p; try < p = Runtime.getRuntime().exec("ls -aF"); BufferedReader br = new BufferedReader( new InputStreamReader(p.getInputStream())); while ((s = br.readLine()) != null) System.out.println("line: " + s); p.waitFor(); System.out.println ("exit: " + p.exitValue()); p.destroy(); >catch (Exception e) <> > > 

When compiled and run, it outputs:

line: ./ line: ../ line: .classpath* line: .project* line: bin/ line: src/ exit: 0 

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 .

Ok, thanks. I worried that using p.exitValue() might have some esoteric advantage. So it's just unecessary bloat in the Process API.

You can also write a shell script file and invoke that file from the java code. as shown below

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.

You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((s = stdInput.readLine()) != null)

try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like: cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort in this program will become: Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();

You can call run-time commands from java for both Windows and Linux.

import java.io.*; public class Test < public static void main(String[] args) < try < Process process = Runtime.getRuntime().exec("pwd"); // for Linux //Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line=reader.readLine())!=null) < System.out.println(line); >> catch(Exception e) < System.out.println(e); >finally < process.destroy(); >> > 
Runtime run = Runtime.getRuntime(); //The best possible I found is to construct a command which you want to execute //as a string and use that in exec. If the batch file takes command line arguments //the command can be constructed a array of strings and pass the array as input to //the exec method. The command can also be passed externally as input to the method. Process p = null; String cmd = "ls"; try < p = run.exec(cmd); p.getErrorStream(); p.waitFor(); >catch (IOException e) < e.printStackTrace(); System.out.println("ERROR.RUNNING.CMD"); >finally

The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:

public static List execute(final String command) throws ExecutionFailedException, InterruptedException, IOException < try < return execute(command, 0, null, false); >catch (ExecutionTimeoutException e) < return null; >/* Impossible case! */ > public static List execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException < return execute(command, 0, null, true); >public static List execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException < Process process = new ProcessBuilder().command("bash", "-c", command).start(); if(timeUnit != null) < if(process.waitFor(timeout, timeUnit)) < if(process.exitValue() == 0) < return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8); >else < throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8)); >> else < if(destroyOnTimeout) process.destroy(); throw new ExecutionTimeoutException("Execution timed out: " + command); >> else < if(process.waitFor() == 0) < return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8); >else < throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8)); >> > public static class ExecutionFailedException extends Exception < private static final long serialVersionUID = 1951044996696304510L; private final int exitCode; private final ListerrorOutput; public ExecutionFailedException(final String message, final int exitCode, final List errorOutput) < super(message); this.exitCode = exitCode; this.errorOutput = errorOutput; >public int getExitCode() < return this.exitCode; >public List getErrorOutput() < return this.errorOutput; >> public static class ExecutionTimeoutException extends Exception < private static final long serialVersionUID = 4428595769718054862L; public ExecutionTimeoutException(final String message) < super(message); >> 

Источник

how to run a command at terminal from java program?

Update: As suggested by xav, it is advisable to use ProcessBuilder instead:

String[] args = new String[] ; Process proc = new ProcessBuilder(args).start(); 

Usage of Runtime.exec() is now discouraged: use shall use ProcessBuilder instead (docs.oracle.com/javase/7/docs/api/java/lang/…)

I vote for Karthik T's answer. you don't need to open a terminal to run commands.

// file: RunShellCommandFromJava.java import java.io.BufferedReader; import java.io.InputStreamReader; public class RunShellCommandFromJava < public static void main(String[] args) < String command = "ping -c 3 www.google.com"; Process proc = Runtime.getRuntime().exec(command); // Read the output BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = ""; while((line = reader.readLine()) != null) < System.out.print(line + "\n"); >proc.waitFor(); > > 
$ javac RunShellCommandFromJava.java $ java RunShellCommandFromJava PING http://google.com (123.125.81.12): 56 data bytes 64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms 64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms 64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms --- http://google.com ping statistics --- 3 packets transmitted, 3 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms 

Источник

Читайте также:  Linux mint проверка wifi
Оцените статью
Adblock
detector