Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用输入在java中运行bash脚本_Java - Fatal编程技术网

如何使用输入在java中运行bash脚本

如何使用输入在java中运行bash脚本,java,Java,我尝试在Java程序中运行bash脚本文件,我使用以下方法: Runtime rt = Runtime.getRuntime(); try { Process proc = rt.exec("THE PATH FILE"); BufferedReaderinput=newBufferedReader(newInputStreamReader(proc.getInputStream())); String line=null; while((

我尝试在Java程序中运行bash脚本文件,我使用以下方法:

Runtime rt = Runtime.getRuntime();

try {           
  Process proc = rt.exec("THE PATH FILE");        
  BufferedReaderinput=newBufferedReader(newInputStreamReader(proc.getInputStream()));
  String line=null;
  while((line=input.readLine()) != null) {
    System.out.println(line);
   }
} catch (IOException ex) {
  System.out.println(ex.toString());
}
但是,当我从命令行运行bash脚本时,我在bash脚本中使用$1作为输入,我想在Java程序中使用它来获得正确的输出。
如何在Java程序中实现这一点

在Java应用程序中读取输入,然后启动一个新流程,如下所示:

bash myfile.sh arg[0] arg[1] arg[n]

正如Mike Thomsen所建议的,您可以将命令行参数输入java应用程序,并将它们传递到脚本文件中,如下所示

StringBuilder cmdLineArgs = new StringBuilder();  

for(String arg:args){   //in case you may have variable number of arguments
    cmdLineArgs.append(arg).append(" ");
}
现在将cmdLineArgs中收集的参数传递给脚本

Process proc = rt.exec("YOUR SCRIPT " + cmdLineArgs.toString()); 

我认为这个问题没有标签的帮助;在bash脚本中使用$1意味着您读取了第一个参数。据我所知,您尝试通过stdin输入数据。