2017-01-02 199 views
-6

如何使用输入参数(如“./flows.sh suspend”)执行shell脚本文件并将结果打印到在linux中使用java的文件?如何使用java执行shell脚本

+1

_“如果可能,请回复完整的代码”_ - 保证吸引downvotes并关闭您的问题。 StackOverflow不是一个“给我teh codez”网站,并且在没有显示任何努力的情况下询问代码被认为是粗鲁和偏离主题。 –

回答

1

这是一个简单的代码来执行shell脚本并读取其输出:

import java.io.*;                

public class Test {               
    public static void main(String[] args) throws Exception {     
    String[] command = { "./flows.sh", "suspend" };   
    Process process = Runtime.getRuntime().exec(command);      
    BufferedReader reader = new BufferedReader(new InputStreamReader( 
     process.getInputStream()));           
    String s;                 
    while ((s = reader.readLine()) != null) {         
     System.out.println("Script output: " + s); // Replace this line with the code to print the result to file      
    }                   
    }                   
}  

要打印到文件时,只需更换的System.out.println的代码写入到文件

+0

它......比这更复杂。仅仅对于初学者来说,'。/'是指什么,shell在哪里介入? –

+1

@JimGarrison'。/'指向当前目录,并且需要抑制PATH查找。解释脚本的shell由内核根据脚本的shebang生成。没有比这更多的东西了,使用ProcessBuilder可以更轻松地将重定向直接设置到文件中。 –

+0

@JimGarrison这是另一个问题......我只是把一个工作解决方案,如何从Java执行一个shell脚本并获得它的输出,因为我认为它是主要问题 – xBlackout