How to run Linux program from Java code

五迷三道 提交于 2019-12-13 00:28:04

问题


I am trying to create a disk space from Java code using qemu-img so I instantiated process and runtime classes. When run the program the command is not executed though I used the same mechanism for similar execution and it work fine. So I am wondering whether I miss something here.

StringBuilder commandBuilder = new StringBuilder("qemu-img create -f "+chosenStorageType+" ~/"+storageName+".img "+storageSize+"M");
System.out.println(commandBuilder);
String command = commandBuilder.toString();
System.out.println("this is the correct one: "+command);

System.out.println("Creating the image...");
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
    process = runtime.exec(command);
    System.out.println("from process try..catch");
} catch (IOException e1) {
    e1.printStackTrace();
    System.out.println(e1.getMessage());
}finally{
    System.out.println("from finally entry");
    process.destroy();
}

the output is as following:

qemu-img create -f raw ~/testSPACE.img 23.0M

this is the correct one: /qemu-img create -f raw ~/testSPACE.img 23.0M
Creating the image...
from process try..catch
from finally entry

But if I go to the directory the file isn't created.

Just to test it if I copy the output into terminal everything works like a charm.


回答1:


The tilde (~) here

" ~/"+storageName+".img "

is interpreted by the shell as meaning your home directory. I would substitute the real path.

Note also that you need to be consuming the process stdout/err, and collecting the error code of the process (and checking it!) via Process.waitFor()



来源:https://stackoverflow.com/questions/15544386/how-to-run-linux-program-from-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!