Bạn có bao giờ muốn thực thi một dòng lệnh từ java giống như trên terminal? Bài viết này sẽ giúp bạn làm điều đó một cách đơn giản. Lưu ý là mình làm trên Ubuntu, do đó trên Windows hoặc một số Distro khác của Linux có thể khác một chút.

Have you ever want to execute a command line from java like on terminal? This post will help you do it a simple way. Please note that I do it on Ubuntu, so on windows or other linux distros differ slightly.

Giả sử bạn đã cài đặt vlc và giờ bạn muốn mở video chim_trang_mo_coi.mp4 tại /home/nguyenvanquan7826/Desktop/chim_trang_mo_coi.mp4 bằng vlc. Bạn viết chương trình như sau rồi chạy, vlc sẽ mở video đó cho bạn ngay lập tức.

Assuming you have installed vlc and now you want to open video chim_trang_mo_coi.mp4 in /home/nguyenvanquan7826/Desktop/chim_trang_mo_coi.mp4 by vlc. You write following program and run it. Vlc will opent it for you immediately.

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();
		}
	}
}

Như bạn đã thấy thì chuỗi command chính là lệnh thực thi giống như khi bạn gõ ở terminal.
Thêm một chút nữa, nếu bạn có một chương trình C đã được biên dịch. Giờ bạn muốn chạy nó? Giả sử chương trình đó in ra một chuỗi và bạn muốn chuỗi đó được in ra thì cần phải lấy InputStream của chuơng trình C đó

As you can see, the string command is execute like when you type in terminal.
Addition, if you have a C program completed. You want to run it? Assuming this program print a string and you want to display this string, you need to get InputStream of the C program.

#include <stdio.h>

int main (int argc, char *argv[])
{
	printf("The program is completed in C and called by java\n");
	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

Bài viết có tham khảo tại: stackoverflow.com