【问题标题】:Runtime.getRuntime().exec(), how to execute file from website link?Runtime.getRuntime().exec(),如何从网站链接执行文件?
【发布时间】:2012-08-29 09:09:51
【问题描述】:

到目前为止,我已经让这条线完美运行,它在我的计算机上执行 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");

【问题讨论】:

    标签: java runtime execute calc


    【解决方案1】:

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

    【讨论】:

    • @KarleeCorinne 点击上面写着下载文件的链接,它有下载链接并将其保存为文件的示例代码。只需将"C:/mura-newest.zip" 替换为您要保存的文件即可。
    • 是的,但它看起来包含很多不必要的代码。另外,如果我将它放在目录 C:/Windows/System32/ 中,是否需要通过执行 C://Windows///System32// 来转义字符?然后对于运行时,我可以只做 Runtime.getRuntime().exec("file.exe"); ?
    • @KarleeCorinne 你可以跳过所有的打印输出和计时器,但你需要其他一切。您可以使用当前目录,如:new File("file.exe") 然后Runtime.getRuntime().exec("file.exe")
    • 当前目录是什么?
    • @KarleeCorinne 无论你在哪里运行你的 java 程序
    【解决方案2】:

    使用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) {}
        }
    }
    

    【讨论】: