JAVA执行LINUX命令
public static void main(String[] args) throws Exception { Process proc = Runtime.getRuntime().exec("/bin/bash", null, new File("/bin")); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true); out.println("cd"); out.println("ls"); out.println("pwd"); out.println("exit"); String line; while ((line = in.readLine()) != null) System.out.println(line); proc.waitFor(); in.close(); out.close(); proc.destroy(); }
注:/bin/bash 必须先执行,等同于#!/bin/bash的命令
PrintWriter构造时候添加参数true的作用是每次println都会刷新缓存区域。无需手动out.flush();
相关推荐
farwang 2020-11-25
星愿心愿 2020-11-24
tianhuak 2020-11-24
zhjn0 2020-11-24
昭君出塞 2020-11-23
bluecarrot 2020-11-23
linuxwcj 2020-10-21
以梦为马不负韶华 2020-10-20
彼岸随笔 2020-10-20
yutou0 2020-10-17
applecarelte 2020-10-16
ourtimes 2020-10-16
waterhorse 2020-09-19
MRFENGG 2020-11-11
rainandtear 2020-10-30
kyssfanhui 2020-10-20
liuhangtiant 2020-10-20