1 // Example showing how to create a disk image.
5 import java.util.HashMap;
6 import com.redhat.et.libguestfs.*;
8 public class CreateDisk
10 static String output = "disk.img";
12 public static void main (String[] argv)
15 GuestFS g = new GuestFS ();
17 // Create a raw-format sparse disk image, 512 MB in size.
18 RandomAccessFile f = new RandomAccessFile (output, "rw");
19 f.setLength (512 * 1024 * 1024);
22 // Set the trace flag so that we can see each libguestfs call.
25 // Set the autosync flag so that the disk will be synchronized
26 // automatically when the libguestfs handle is closed.
27 g.set_autosync (true);
29 // Attach the disk image to libguestfs.
30 Map<String, Object> optargs = new HashMap<String, Object>() {
32 put ("format", "raw");
33 put ("readonly", Boolean.FALSE);
36 g.add_drive_opts (output, optargs);
38 // Run the libguestfs back-end.
41 // Get the list of devices. Because we only added one drive
42 // above, we expect that this list should contain a single
44 String[] devices = g.list_devices ();
45 if (devices.length != 1)
46 throw new Error ("expected a single device from list-devices");
48 // Partition the disk as one single MBR partition.
49 g.part_disk (devices[0], "mbr");
51 // Get the list of partitions. We expect a single element, which
52 // is the partition we have just created.
53 String[] partitions = g.list_partitions ();
54 if (partitions.length != 1)
55 throw new Error ("expected a single partition from list-partitions");
57 // Create a filesystem on the partition.
58 g.mkfs ("ext4", partitions[0]);
60 // Now mount the filesystem so that we can add files.
61 g.mount_options ("", partitions[0], "/");
63 // Create some files and directories.
65 String message = "Hello, world\n";
66 g.write ("/hello", message.getBytes());
69 // This one uploads the local file /etc/resolv.conf into
71 g.upload ("/etc/resolv.conf", "/foo/resolv.conf");
73 // Because 'autosync' was set (above) we can just close the handle
74 // and the disk contents will be synchronized. You can also do
75 // this manually by calling g#umount_all and g#sync.
77 // Note also that handles are automatically closed if they are
78 // reaped by the garbage collector. You only need to call close
79 // if you want to close the handle right away.
82 catch (Exception exn) {
83 System.err.println (exn);