JAVA 调用 shell 执行

JAVA 直接调用 shell 执行,各个操作系统都支持, 收藏下

下面的示例是调用windows cmd下的ipconfig

public class CallShell {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Process process = Runtime.getRuntime().exec("ipconfig");
			InputStream is=process.getInputStream();
			byte[] b=new byte[1024];
			StringBuilder sb=new StringBuilder();
			while(is.read(b)>0){
				sb.append(new String(b));
			}
			System.out.println(sb.toString());
			
			int exitValue = process.waitFor();
			if (0 != exitValue) {
				System.out.println(exitValue);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用`Runtime`类或`ProcessBuilder`类来调用Shell命令。下面是两种常见的方法: 1. 使用`Runtime`类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class ShellCommand { public static void main(String[] args) { try { // 执行Shell命令 String command = "ls -l"; Process process = Runtime.getRuntime().exec(command); // 读取命令输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 int exitCode = process.waitFor(); System.out.println("Exit Code: " + exitCode); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用`ProcessBuilder`类: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class ShellCommand { public static void main(String[] args) { try { // 构建Shell命令 ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l"); // 执行Shell命令 Process process = processBuilder.start(); // 读取命令输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 int exitCode = process.waitFor(); System.out.println("Exit Code: " + exitCode); } catch (Exception e) { e.printStackTrace(); } } } ``` 这两种方法都可以用于调用Shell命令并获取输出结果。你可以根据需要修改命令和处理输出的方式。注意,调用Shell命令可能存在安全风险,请谨慎使用,并确保只执行可信任的命令。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值