开发者

Runtime.getruntime().exec() doesn't work on Linux

I have a Java Runtime.getRuntime().exec() problem. I run my java app on Linux and just need to execute a basic task: copy and rename a file using cp command. However, it doesn't seem to work.

This is my chunk of code to cal开发者_如何学编程l the Runtime.getRuntime().exec():

String command = "cp -f '" + old_path + "' " + song_info[6] + ".mp3";                
System.out.println(command);
log.info(command);
            try{
                p = Runtime.getRuntime().exec(command);
                int returnCode;
                try {
                    returnCode = p.waitFor();
                    System.out.println("Return code = " + returnCode);
                } catch (InterruptedException ex) {
                    java.util.logging.Logger.getLogger(Import.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch(IOException e){log.error(e);}

When I run the java app the command for each loop is something like this

cp -f '/temp_storage/LoveSongs/28.I miss you.mp3' /music_storage/data/0/0/1/108.mp3

If I copy that log line and run it in the command line, it works perfectly. However the result from java app always return code 1 (which indicate failure). Even including /bin/bash -c before the command string, it still doesn't work.

Any suggestion why? I've just install JRE and JDK on that server. When I type java -version I got:

java version "1.6.0_17" OpenJDK Runtime Environment (IcedTea6 1.7.10) (rhel-1.20.b17.el5-x86_64) OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)


AFAIK, if you command has multiple command line parameters you need to supply them in a String[], have you tried that? Furthermore if you need to copy files around you can use FileUtils or Guava libraries (dont remember what it's called there)

see this relevant thread about copying files


Does the user that the application is running under have the necessary permissions? And from the process, have you tried getting hold of stderr to see if there is anything useful in there?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜