JavaDemo——java调用Linux命令

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/82465185

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系统上运行。

结果:

猜你喜欢

转载自blog.csdn.net/FlyLikeButterfly/article/details/82465185