如何从 Java 代码运行 Linux 程序 [英] How to run Linux program from Java code

查看:61
本文介绍了如何从 Java 代码运行 Linux 程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 qemu-img 从 Java 代码创建磁盘空间,因此我实例化了进程和运行时类.运行程序时,虽然我使用相同的机制进行类似的执行,但不会执行该命令,并且它工作正常.所以我想知道我是否在这里错过了什么.

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();
}

输出如下:

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.

推荐答案

波浪号 (~) 在这里

" ~/"+storageName+".img "

被 shell 解释为您的主目录.我会替换真实路径.

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

还要注意,你需要消耗进程stdout/err,并收集进程的错误代码(并检查它!)通过 Process.waitFor()

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()

这篇关于如何从 Java 代码运行 Linux 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆