简体   繁体   English

如何从Java代码运行Linux程序

[英]How to run Linux program from Java code

I am trying to create a disk space from Java code using qemu-img so I instantiated process and runtime classes. 我试图使用qemu-img从Java代码创建磁盘空间,所以我实例化了进程和运行时类。 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. 只是为了测试一下,如果我将输出复制到终端,那么一切都像一个超级按钮。

The tilde ( ~ ) here 这里的波浪号( ~

" ~/"+storageName+".img "

is interpreted by the shell as meaning your home directory. Shell将其解释为意味着您的主目录。 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() 还要注意,您需要使用流程stdout / err ,并通过Process.waitFor()收集流程的错误代码(并对其进行检查!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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