1

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.

user2023107
  • 65
  • 1
  • 9
  • 3
    Can you verify that `~` is being expanded properly? Try putting a full absolute path in there and see if it works. Sometimes that kind of expansion behaviour is provided by the shell and is therefore not going to work for some command-invocation tasks. – Gian Mar 21 '13 at 10:05
  • yeah while providing absolute path: StringBuilder commandBuilder = new StringBuilder("qemu-img create -f "+chosenStorageType+" /home/dartron/"+storageName+".img"+storageSize+"M"); it does the same thing just prints out the lines but doesnt execute the command – user2023107 Mar 21 '13 at 22:21

1 Answers1

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

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • To emphasize more strongly, the `~` symbol requires a shell to be interpreted, which a Java `Process` does not have by default. You would have to invoke the shell as one of your commands, ie, for Linux, by making the first command `/usr/bin/sh`. – Perception Mar 21 '13 at 10:27
  • even while providing absolute path: StringBuilder commandBuilder = new StringBuilder("qemu-img create -f "+chosenStorageType+" /home/dartron/"+storageName+".img"+storageSize+"M"); it does the same thing just prints out the lines but doesnt execute the command – user2023107 Mar 21 '13 at 22:29
  • @user2023107 Try the absolute path to `qemu-img` as well. – artless noise Mar 25 '13 at 02:43