JavaDemo——java调用Linux命令

Demo:

/**
 * createtime : 2018年9月6日 下午5:14:20
 */
package com.useLinuxCmd;

import java.io.IOException;

/**
 * TODO
 * @author XWF
 */
public class TestLinuxCmd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Process proc = null;
		try {
			//创建文件
			String touchCmd = "touch hello.txt";
			proc = Runtime.getRuntime().exec(touchCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//管道类命令要用这种方式
			String[] cmds = {"/bin/sh","-c","echo helloworld > hello.txt"};
			proc = Runtime.getRuntime().exec(cmds);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//删除文件
			String rmCmd = "rm -rf needrm.txt";
			proc = Runtime.getRuntime().exec(rmCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//执行文件
			String bashCmd = "bash mkfolder.sh";
			proc = Runtime.getRuntime().exec(bashCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

mkfolder.sh脚本:

#!/bin/sh
mkdir myfolder

 把java代码生成jar包,放到linux系统上运行。

结果:

2021.12.20添加

通过Runtime调用命令并获得结果:

/**
 * 2021年12月20日下午3:48:23
 */
package testRunCmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author XWF
 *
 */
public class TestRunCmd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			String cmd = "ls -ahl";
			
			String line = null;
			StringBuilder sb = new StringBuilder();
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(new String[] {"/bin/sh", "-c", cmd});
			BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			while((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			String result = sb.toString();
			
			System.out.println("执行结果:" + result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

放到linux上运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值