Java执行Shell脚本

Linux 系统下采用 Java 执行 Shell 脚本,直接上代码:

package com.smbea.demo;

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

/**
 * 执行 Shell 脚本
 * @author hapday
 * @date 2017年3月14日 @Time 下午2:28:22
 */
public class ChmodShell {
	/**
	 * 更新文件夹的权限
	 * @param folderName
	 */
	public static void updateFolderAuth(String folderName) {
		String command = "chmod a+x mk.sh";		// 设置 shell 脚本的为“可读写”与“可执行”
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			// 阻塞当前线程,直到 command 命令执行完毕
			process.waitFor();		
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		
		// 要执行的 shell 脚本
		command = "bash mk.sh " + folderName; 	// 也可以是 ksh、sh 等
		
		try {
			process = Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		try {
			while ( null != (bufferedReader.readLine()) );
			
			bufferedReader.close();		// 关闭缓冲流
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			// 阻塞当前线程,直到 command 命令执行完毕
			process.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String parameter = "test";
		
		if(null != args && 0 < args.length) {
			parameter = args[0];
		}
		
		updateFolderAuth(parameter);
	}
}

  

原文地址:https://www.cnblogs.com/hapday/p/6548693.html