如何在Java中运行bash脚本(下载文件)? [英] How can I run a bash script (which downloads a file) in Java?

查看:159
本文介绍了如何在Java中运行bash脚本(下载文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mac OS X Lion中运行,我需要使用命令行中的脚本从远程服务器检索文件。我试图在代码中使用的命令是bash / my / path / here / myscript,我已经使用以下代码从命令行(atos)运行另一个进程。

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.

推荐答案

使用以下代码 -

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.

这篇关于如何在Java中运行bash脚本(下载文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆