[Java的] 执行用java命令行 – 在java中执行命令行
你永远不希望从像Java终端执行命令? 本文将帮助你做到这一点的简单方法. 请注意,我在Ubuntu, 所以在Windows或其他Linux发行版可能稍有不同.
假设你已经安装 VLC 现在你要打开的视频 chim_trang_mo_coi.mp4 在 /家用/ nguyenvanquan7826 /桌面/ chim_trang_mo_coi.mp4 用VLC. 你写一个这样的程序并运行, VLC视频将立即打开它你.
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(); } } }
正如你所看到的,字符串 命令 命令执行,就好像你在终端输入.
添加多一点, 如果你有一个C程序被编译. 现在你要运行它? 假设你要打印出需要采取该程序在一个字符串和字符串 的InputStream 该程序的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(); } } }
在文章中引用: stackoverflow.com
最新评论