-1

So far I've got this line to work perfectly and it executes calc.exe on my computer:

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

But how can I download and execute a file from a website link? For example http://website.com/calc.exe

I found this code on the web but it doesn't work:

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

2 Answers2

0

You use URL and/or URLConnection, download the file, save it somewhere (current working directory, or a temp directory, for example), then execute it using the Runtime.getRuntime().exec().

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • @KarleeCorinne click on the link where it says **download the file**, it's got sample code for downloading a link and saving it as a file. Just replace the `"C:/mura-newest.zip"` with the file you want to save it as. – Jon Lin Aug 29 '12 at 01:09
  • Yes but it looks like it contains a lot of unnecessary code. Also if I place it in the directory C:/Windows/System32/ Do I need to escape the characters by doing C://Windows///System32// ? And then for the runtime, I can just do Runtime.getRuntime().exec("file.exe"); ? – Karlee Corinne Aug 29 '12 at 01:23
  • @KarleeCorinne you can skip all of the printouts and the timer, but you need everything else. You can use the current directory, as in: `new File("file.exe")` and then `Runtime.getRuntime().exec("file.exe")` – Jon Lin Aug 29 '12 at 01:28
  • What is the current directory though? – Karlee Corinne Aug 29 '12 at 01:59
  • @KarleeCorinne it is whereever you run your java program – Jon Lin Aug 29 '12 at 02:53
0

Using this answer as a starting point you could do this: (this uses 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) {}
    }
}
Community
  • 1
  • 1
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124