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) 2014, HerongYang.com, All Rights Reserved.
 */
import java.io.*;
public class CheckDisk {
   private static String cmd = "C:\\Windows\\System32\\chkdsk f:";
   public static void main(String[] a) {
      Runtime rt = Runtime.getRuntime();
      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());
      }
   }
}

Note that the program assumes that you have a storage device connected as drive F:.

Output:

The type of the file system is FAT.
Volume UDISK 2.0 created 6/8/2012 10:10 PM
Windows is verifying files and folders...
File and folder verification is complete.
Windows has checked the file system and found no problems.

  259,756,032 bytes total disk space.
       16,384 bytes in 4 folders.
    9,371,648 bytes in 15 files.
  250,368,000 bytes available on disk.

        4,096 bytes in each allocation unit.
       63,417 total allocation units on disk.
       61,125 allocation units available on disk.

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

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 StringBuffer - The String Buffer Class

System Properties and Runtime Object Methods

 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

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials

 References

 PDF Printing Version