[Java] Thực thi dòng lệnh với java – Execute command line in java

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.

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.

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 đó

#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

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