[Java] Execute the command line with java – Execute command line in java

You never want to execute a command from a terminal like java? This article will help you do it in a simple way. Note that I do on Ubuntu, so on Windows or some other distro of Linux may vary slightly.

Assuming you've installed vlc and now you want to open the video chim_trang_mo_coi.mp4 at /home / nguyenvanquan7826 / Desktop / chim_trang_mo_coi.mp4 by vlc. You write a program like this and run, vlc video will open it for you right away.

package executecommandline;

import java.io.IOException;

class ExecuteCommandLine {
	private native void print();

	public static void main(String[] args) {
		String command = "vlc /home/nguyenvanquan7826/Desktop/chim_trang_mo_coi.mp4";
		try {
			Process p = Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

As you saw, the chain command command is executed just as if you typed in terminal.
Add a little more, if you have a C program has been compiled. Now you want to run it? Assuming that program prints out a string and the string that you want to print, you need to take InputStream That program's C

#include <stdio.h>

int main (int argc, char *argv[])
{
	printf("The program is completed in C and called by javan");
	return 0;
}
package executecommandline;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class ExecuteCommandLine {
	private native void print();

	public static void main(String[] args) {
		String command = "/home/nguyenvanquan7826/Desktop/temp";
		try {
			Process p = Runtime.getRuntime().exec(command);
			String line = "";
			BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
			BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			while ((line = bri.readLine()) != null) {
				System.out.println(line);
			}
			bri.close();
			while ((line = bre.readLine()) != null) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

execute command line in java

Article referenced in: stackoverflow.com