简体   繁体   中英

Runtime.exec command not working

I have a java application that downloads a file from a web service using wget. When executing the command through java it returns with: "wget: not an http or ftp url:" When i execute the command directly it runs without problems. Here is my code:

try {
        Debug.println("Starting copy of "+srcFile+" to "+destFile);
        String command = "wget -O " + destFile + " \""+ srcFile +"\"";
        Process p = Runtime.getRuntime().exec(command);
        int exitCode = p.waitFor();

        if(Debug.isDebugMode())
        {
            Debug.println(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String s;
            while((s = stdInput.readLine()) != null)
            {
                Debug.println(s);
            }
        }
        Debug.println("Finished with code: " + String.valueOf(exitCode));
    } 
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;

And this is the output:

24/04/2013 10:11:05 Starting copy of stoppenmetroken.webcolors.local/service/track?track=3b1ac68a288345c183a08c714901a398&mac=089000A09090 to /opt/byato/data/song/3b1ac68a288345c183a08c714901a398
24/04/2013 10:11:05 wget -O /opt/byato/data/song/3b1ac68a288345c183a08c714901a398 "stoppenmetroken.webcolors.local/service/track?track=3b1ac68a288345c183a08c714901a398&mac=089000A09090"
24/04/2013 10:11:05 wget: not an http or ftp url: "http://stoppenmetroken.webcolors.local/service/track?track=3b1ac68a288345c183a08c714901a398&mac=089000A09090"
24/04/2013 10:11:05 Finished with code: 1

ps: i removed the http:// part of the output because i dont have enough reputation points -.-

What am i missing?

Can you try to execute the command like this :

Process p = Runtime.getRuntime().exec("/bin/bash -c "+command); //for linux

or

Process p = Runtime.getRuntime().exec("cmd.exe /c "+command); //for Windows

Sometimes we need to explicitly invoke Linux shell or command prompt.

Hope this will work.

I suspect this:

String command = "wget -O " + destFile + " \""+ srcFile +"\"";

is the problem. When you run in a shell, the quotes around the URL will be removed. However when you run via Java you're not running via a shell and your URL starts with "http... (look closely at the error message).

If you don't want Runtime.exec() t o parse and split your arguments then you might consider the variant that takes individual arguments . A more efficient solution still would be to download using HttpComponents .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM