How can I run a bash script (which downloads a file) in Java?

大城市里の小女人 提交于 2019-12-25 17:18:51

问题


Running in Mac OS X Lion, I need to retrieve a file from a remote server using a script in the command line. The command I'm trying to use in code is "bash /my/path/here/myscript" and I already run another process from the command line (atos) using the code below.

Process proc = Runtime.getRuntime().exec(cmd);

But while debugging, the program continues without error, yet the script does appear to have actually run. Furthermore, there should be a pause of several seconds while the script retrieves the file, yet my program continues to execute immediately. The script itself works as intended when run from the terminal. I'm a little stumped on how to get this to work, so any help would be greatly appreciated.


回答1:


Got it to work with the following code -

Process proc = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
proc.waitFor();

while (in.ready()) {
    System.out.println(in.readLine());
}

The other thing that was an issue is that the script would download to the current working directory rather than the location of the script itself (as intended). So the script would run correctly while my program would continue to fail to find the downloaded file. Hope this helps.



来源:https://stackoverflow.com/questions/10711308/how-can-i-run-a-bash-script-which-downloads-a-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!