Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

exec() - Executing Operating System Commands

This section provides a tutorial example on how to calculate memory usage of a large array.

The Runtime instance also offers methods for the Java application program to execute an operating system command as a subprocess. The following program uses the exec() method to execute "chkdsk" command:

/**
 * CheckDisk.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
import java.io.*;
public class CheckDisk {
   private static String cmd = "c:\\winnt\\system32\\chkdsk /i /c c:";
   public static void main(String[] a) {
      Runtime rt = Runtime.getRuntime();
      Process p = null;
      try {
         Process p = rt.exec(cmd);
         Reader in = new InputStreamReader(p.getInputStream());
         int c = in.read();
         while (c!=-1) {
            System.out.print((char)c);
            c = in.read();
         }
      } catch (IOException e) {
         System.out.println(e.toString());
      }
   }
}

Output:

The type of the file system is NTFS.
Volume label is Local Disk.

WARNING!  F parameter not specified.
Running CHKDSK in read-only mode.

WARNING!  I parameter specified.
WARNING!  C parameter specified.
Your drive may still be corrupt even after running CHKDSK.

CHKDSK is verifying files (stage 1 of 3)...
File verification completed.
CHKDSK is verifying indexes (stage 2 of 3)...
Index verification completed.
CHKDSK is verifying security descriptors (stage 3 of 3)...
Security descriptor verification completed.

   2096482 KB total disk space.
   1825111 KB in 20535 files.
      7004 KB in 1919 indexes.
         0 KB in bad sectors.
     42432 KB in use by the system.
     12544 KB occupied by the log file.
    221934 KB available on disk.

       512 bytes in each allocation unit.
   4192964 total allocation units on disk.
    443869 allocation units available on disk.

Note that how the output of the subprocess captured and reprinted on the JVM console.

Sections in This Chapter

JVM and OS System Properties

System.setProperty() - Setting Your Own Properties

Runtime.getRuntime() - Getting the Runtime Object

freeMemory() - Getting JVM Free Memory Information

Calculating Memory Usage of an Array

exec() - Executing Operating System Commands

Dr. Herong Yang, updated in 2008
exec() - Executing Operating System Commands