Runtime.getRuntime()。exec(),如何从网站链接执行文件?

时间:2012-08-29 00:58:22

标签: java runtime execute calc

到目前为止,我已经让这条线路完美地工作了,它在我的电脑上执行了calc.exe:

Runtime.getRuntime().exec("calc.exe");

但是如何从网站链接下载并执行文件?例如http://website.com/calc.exe

我在网上发现了这段代码,但它不起作用:

Runtime.getRuntime().exec("bitsadmin /transfer myjob /download /priority high http://website.com/calc.exe c:\\calc.exe &start calc.exe");

2 个答案:

答案 0 :(得分:0)

您使用URL和/或URLConnectiondownload the file,将其保存在某处(例如当前工作目录或临时目录),然后使用{{1}执行它}}

答案 1 :(得分:0)

使用this answer作为起点,您可以这样做:(这使用HttpClient

public static void main(String... args) throws IOException {
    System.out.println("Connecting...");
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://website.com/calc.exe");
    HttpResponse response = client.execute(get);

    InputStream input = null;
    OutputStream output = null;
    byte[] buffer = new byte[1024];

    try {
        System.out.println("Downloading file...");
        input = response.getEntity().getContent();
        output = new FileOutputStream("c:\\calc.exe");
        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
        System.out.println("File successfully downloaded!");
        Runtime.getRuntime().exec("c:\\calc.exe");

    } finally {
        if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
}