Java/Development Class/Runtime
Содержание
- 1 Calculate process elapsed time
- 2 Command and its arguments supplied in an array
- 3 Determine when the application is about to exit
- 4 Execute a command from code
- 5 Execute a command with an argument that contains a space
- 6 Execute a command with an argument that contains a space: use array
- 7 Execute a command with more than one argument
- 8 Execute system command
- 9 From Runtime.exec() to ProcessBuilder
- 10 Get amount of free memory within the heap in bytes.
- 11 Get current size of heap in bytes
- 12 Get maximum size of heap in bytes.
- 13 Get Number of Available Processors
- 14 Getting the Size of the Java Memory Heap
- 15 Launch a Unix script with Java
- 16 Minimize all programs on Windows to show the Desktop
- 17 Read all information that the child process sends to its standard output stream
- 18 Read output from a Command execution
- 19 Registering Shutdown Hooks for Virtual Machine
- 20 Runtime.getRuntime().exec
- 21 Send an Input to a Command
Calculate process elapsed time
 
public class Main {
  public static void main(String[] args) {
    long start = System.nanoTime();
    System.out.println("Start: " + start);
    for (int i = 0; i < 100; i++) {
      for (int j = 0; j < 100; j++) {
        System.out.println("asdf");
      }
    }
    long end = System.nanoTime();
    System.out.println("End  : " + end);
    long elapsedTime = end - start;
    System.out.println(elapsedTime + " nano seconds");
  }
}
   
   
Command and its arguments supplied in an array
 
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] commands = new String[] { "grep", "hello world", "/tmp/f.txt" };
    commands = new String[] { "grep", "hello world", "c:\\f.txt" };
    Process child = Runtime.getRuntime().exec(commands);
  }
}
   
   
Determine when the application is about to exit
 
public class Main {
  public static void main(String[] argv) throws Exception {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        System.out.println("Do shutdown work ...");
      }
    });
  }
}
   
   
Execute a command from code
 
public class Main {
  public static void main(String[] argv) throws Exception {
    // Execute a command without arguments
    String command = "ls";
    Process child = Runtime.getRuntime().exec(command);
    // Execute a command with an argument
    command = "ls /tmp";
    child = Runtime.getRuntime().exec(command);
  }
}
   
   
Execute a command with an argument that contains a space
 
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] commands = new String[] { "grep", "hello world", "/tmp/f.txt" };
    commands = new String[] { "grep", "hello world", "c:\\f.txt" };
    Process child = Runtime.getRuntime().exec(commands);
  }
}
   
   
Execute a command with an argument that contains a space: use array
 
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] commands = new String[] { "grep", "hello world", "/tmp/f.txt" };
    commands = new String[] { "grep", "hello world", "c:/f.txt" };
    Process child = Runtime.getRuntime().exec(commands);
  }
}
   
   
Execute a command with more than one argument
 
public class Main {
  public static void main(String[] argv) throws Exception {
    // Execute a command with an argument that contains a space
    String[] commands = new String[] { "grep", "hello world", "/tmp/f.txt" };
    commands = new String[] { "grep", "hello world", "c:\\f.txt" };
    Process child = Runtime.getRuntime().exec(commands);
  }
}
   
   
Execute system command
 
import java.io.IOException;
public class Main {
  public static void main(String[] args) throws IOException {
    String cmd = "cmd.exe /c start ";
    // String file = "c:\\version.txt";
    // String file = "http://www.google.ru";
    // String file = "c:\\";
    // String file = "mailto:author@my.ru";
    String file = "mailto:";
    Runtime.getRuntime().exec(cmd + file);
  }
}
   
   
From Runtime.exec() to ProcessBuilder
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
  public static void main(String args[]) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(args);
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    System.out.printf("Output of running %s is:", Arrays.toString(args));
    while ((line = br.readLine()) != null) {
      System.out.println(line);
    }
  }
}
   
   
Get amount of free memory within the heap in bytes.
 
public class Main {
  public static void main(String[] argv) {
    long heapFreeSize = Runtime.getRuntime().freeMemory();
    System.out.println(heapFreeSize);
  }
}
   
   
Get current size of heap in bytes
 
public class Main {
  public static void main(String[] argv) {
    long heapSize = Runtime.getRuntime().totalMemory();
    System.out.println(heapSize);
  }
}
   
   
Get maximum size of heap in bytes.
 
public class Main {
  public static void main(String[] argv) {
    long heapMaxSize = Runtime.getRuntime().maxMemory();
    System.out.println(heapMaxSize);
  }
}
   
   
Get Number of Available Processors
  
public class Main {
  public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
    int nrOfProcessors = runtime.availableProcessors();
    System.out.println("Number of processors available to the Java Virtual Machine: "
        + nrOfProcessors);
  }
}
// Number of processors available to the Java Virtual Machine: 2
   
   
Getting the Size of the Java Memory Heap
  
public class Main {
  public static void main(String[] argv) throws Exception {
    long heapSize = Runtime.getRuntime().totalMemory();
    long heapMaxSize = Runtime.getRuntime().maxMemory();
    long heapFreeSize = Runtime.getRuntime().freeMemory();
  }
}
   
   
Launch a Unix script with Java
 
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] cmd = { "/bin/sh", "-c", "ls > hello" };
    Runtime.getRuntime().exec(cmd);
  }
}
   
   
Minimize all programs on Windows to show the Desktop
 
public class Main {
  public static void main(String args[]) throws Exception {
    Runtime.getRuntime().exec(
        new String[] {
            "cmd.exe",
            "/c",
            "\"" + System.getenv("APPDATA")
                + "\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf" + "\"" });
  }
}
   
   
Read all information that the child process sends to its standard output stream
  
    
import java.io.InputStream;
class Run2 {
  public static void main(String[] args) throws java.io.IOException {
    if (args.length != 1) {
      System.err.println("usage: java Run pathname");
      return;
    }
    Process p = Runtime.getRuntime().exec(args[0]);
    InputStream is = p.getInputStream();
    int b;
    while ((b = is.read()) != -1)
      System.out.print((char) b);
    try {
      System.out.println("Exit status = " + p.waitFor());
    } catch (InterruptedException e) {
    }
  }
}
   
   
Read output from a Command execution
 
import java.io.InputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    String command = "ls";
    Process child = Runtime.getRuntime().exec(command);
    InputStream in = child.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
      System.out.println((char) c);
    }
    in.close();
  }
}
   
   
Registering Shutdown Hooks for Virtual Machine
 
public class Main implements Runnable {
  public void run() {
    System.out.println("Shutting down");
  }
  public static void main(String[] arg) {
    Runtime runTime = Runtime.getRuntime();
    Main hook = new Main();
    runTime.addShutdownHook(new Thread(hook));
  }
}
   
   
Runtime.getRuntime().exec
  
class Run1 {
  public static void main(String[] args) throws java.io.IOException {
    if (args.length != 1) {
      System.err.println("usage: java Run pathname");
      return;
    }
    Process p = Runtime.getRuntime().exec(args[0]);
    try {
      System.out.println("Exit status = " + p.waitFor());
    } catch (InterruptedException e) {
    }
  }
}
   
   
Send an Input to a Command
 
import java.io.OutputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    String command = "cat";
    Process child = Runtime.getRuntime().exec(command);
    OutputStream out = child.getOutputStream();
    out.write("some text".getBytes());
    out.close();
  }
}
   
