简体   繁体   中英

Executing a Linux command in Terminal from Java

I am currently using a command called "curl" from Terminal in Ubuntu, tu upload my .RDF files to a Virtuoso RDF Store.

curl -T FILE URL -u USER:PASSWORD

I want to automatize these process, so that I create a Java function in eclipse. This code is not working.

String[] command = {"curl -T", FILENAME, URL, "-u", credentials.USERNAME+":"+credentials.PASSWORD};
Runtime.getRuntime().exec(command)

I have also tried with this one. The xterm appears, but it shows this error (even though the file is in the Path of the function):

*"/usr/bin/xterm. Can't execvp "curl" no such a directory or file"*


Runtime.getRuntime().exec("/usr/bin/xterm -e \"curl -T " + FILENAME  
                                                        + " " + URL + "-u " + credentials.USERNAME
                                                        + ":" + credentials.PASSWORD + "\"");

I would appreciate any help on the matter.

Thanks in advance

I have had a hard time trying to get commands run using Runtime.exec() in the past. Anyways I have shifted to using ProcessBuilder as follows:

ProcessBuilder pbuilder = new ProcessBuilder("bash", "-c", <<your command as string>>);
        File err = new File("err.txt");
        try {
            pbuilder.redirectError(err);
            Process p = pbuilder.start();
            p.waitFor();      

        } catch (Exception e) 
        {
             //handle exceptions if any.
        }

The stderr line is optional, for debugging purposes. I am sure that it could be directly printed out to console, but havn't checked on it yet. Will update my answer, once I find more.

You can check out the documentation page here .

PS: Also check if you have the necessary permissions to carry out the desired task.

使用Runtime.exec通常不是一个好主意,为什么不使用Java HTTP API上传文件呢?

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