java——运行linux的shell命名文件

运行linux的shell命名文件

【一】java中运行shell命名api

有时候我们在Linux中运行Java程序时,需要调用一些Shell命令和脚本。而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法:

Process exec(String command)   
在单独的进程中执行指定的字符串命令。   
  
Process exec(String[] cmdarray)   
在单独的进程中执行指定命令和变量。   
  
Process exec(String[] cmdarray, String[] envp)   
在指定环境的独立进程中执行指定命令和变量。   
  
Process exec(String[] cmdarray, String[] envp, File dir)   
在指定环境和工作目录的独立进程中执行指定的命令和变量。   
  
Process exec(String command, String[] envp)   
在指定环境的单独进程中执行指定的字符串命令。   
  
Process exec(String command, String[] envp, File dir)   
在有指定环境和工作目录的独立进程中执行指定的字符串命令。

ps:方法waitFor()

abstract  int waitFor()   
导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。

【二】构建shell脚本

创建echo.sh

#!/usr/bin/env bash

#输出hello java
echo hello java

#创建hello.txt文件
touch hello.txt

#将"hello java"输入到hello.txt文件中
echo hello java > hello.txt

【三】java代码执行shell脚本

package com.shell;

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

/**
 * @author fengwen
 */
public class Main {
    public static void main(String[] args) throws Exception {

        //运行的命名
        String bashCommand = "sh echo.sh";
        Process pro = Runtime.getRuntime().exec(bashCommand);

        //等待脚本执行完毕
        int status = pro.waitFor();

        if (status != 0) {
            System.out.println("Failed to call shell's command ");
        }

        //输出脚本运行的情况
        BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line).append("\n");
        }
        System.out.println(stringBuffer.toString());

    }
}

【四】链接

发布了130 篇原创文章 · 获赞 88 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/wenge1477/article/details/103337292
今日推荐