Java Tutorial/Development/Runtime System

Материал из Java эксперт
Перейти к: навигация, поиск

Demonstrate exec().

   <source lang="java">

class ExecDemo {

 public static void main(String args[]) {
   Runtime r = Runtime.getRuntime();
   Process p = null;
   try {
     p = r.exec("notepad");
   } catch (Exception e) {
     System.out.println("Error executing notepad.");
   }
 }

}</source>





Demonstrate totalMemory(), freeMemory() and gc().

   <source lang="java">

class MemoryDemo {

 public static void main(String args[]) {
   Runtime r = Runtime.getRuntime();
   long mem1, mem2;
   Integer someints[] = new Integer[1000];
   System.out.println("Total memory is: " + r.totalMemory());
   mem1 = r.freeMemory();
   System.out.println("Initial free memory: " + mem1);
   r.gc();
   mem1 = r.freeMemory();
   System.out.println("Free memory after garbage collection: " + mem1);
   for (int i = 0; i < 1000; i++)
     someints[i] = new Integer(i); // allocate integers
   mem2 = r.freeMemory();
   System.out.println("Free memory after allocation: " + mem2);
   System.out.println("Memory used by allocation: " + (mem1 - mem2));
   for (int i = 0; i < 1000; i++)
     someints[i] = null;
   r.gc(); // request garbage collection
   mem2 = r.freeMemory();
   System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);
 }

}</source>





Determine when the application is about to exit

   <source lang="java">

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 ...");
     }
   });
 }

}</source>





Display the amount of free memory in the Java Virtual Machine.

   <source lang="java">

import java.text.DecimalFormat; public class Main {

 public static void main(String[] args) {
   DecimalFormat df = new DecimalFormat("0.00");
   long freeMem = Runtime.getRuntime().freeMemory();
   System.out.println(df.format(freeMem / 1000000F) + " MB");
 }

}</source>





Display the maximum amount of memory

   <source lang="java">

import java.text.DecimalFormat; public class Main {

 public static void main(String[] args) {
   DecimalFormat df = new DecimalFormat("0.00");
   long maxMem = Runtime.getRuntime().maxMemory();
   System.out.println(df.format(maxMem / 1000000F) + " MB");
 }

}</source>





Display the total amount of memory in the Java virtual machine.

   <source lang="java">

import java.text.DecimalFormat; public class Main {

 public static void main(String[] args) {
   DecimalFormat df = new DecimalFormat("0.00");
   long totalMem = Runtime.getRuntime().totalMemory();
   System.out.println(df.format(totalMem / 1000000F) + " MB");
 }

}</source>





Execute a command from code

   <source lang="java">

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);
 }

}</source>





Execute a command with more than one argument

   <source lang="java">

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);
 }

}</source>





Execute system command

   <source lang="java">

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);
 }

}</source>





From Runtime.exec() to ProcessBuilder

   <source lang="java">

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);
   }
 }

}</source>





Get Number of Available Processors

   <source lang="java">

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</source>





Launch a Unix script with Java

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   String[] cmd = { "/bin/sh", "-c", "ls > hello" };
   Runtime.getRuntime().exec(cmd);
 }

}</source>





Milliseconds elapsed since January 1, 1970

   <source lang="java">

import java.util.Properties; public class SystemApp {

 public static void main(String args[]) {
   long time = System.currentTimeMillis();
   System.out.println(time);
   Properties p = System.getProperties();
   p.list(System.out);
   System.exit(13);
 }

}</source>





Read output from a Command execution

   <source lang="java">

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

}</source>





Registering Shutdown Hooks for Virtual Machine

   <source lang="java">

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));
 }

}</source>





Send an Input to a Command

   <source lang="java">

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

}</source>





System.getProperty

   <source lang="java">

class ShowUserDir {

 public static void main(String args[]) {
   System.out.println(System.getProperty("user.dir"));
 }

} The following properties are available: file.separator java.specification.version java.vm.version java.class.path java.vendor line.separator java.class.version java.vendor.url os.arch java.rupiler java.version os.name java.ext.dirs java.vm.name os.version java.home java.vm.specification.name path.separator java.io.tmpdir java.vm.specification.vendor user.dir java.library.path java.vm.specification.version user.home java.specification.name java.vm.vendor user.name java.specification.vendor</source>





Timing program execution.

   <source lang="java">

class Elapsed {

 public static void main(String args[]) {
   long start, end;
   System.out.println("Timing a for loop from 0 to 1,000,000");
   start = System.currentTimeMillis(); // get starting time
   for (int i = 0; i < 1000000; i++)
     ;
   end = System.currentTimeMillis(); // get ending time
   System.out.println("Elapsed time: " + (end - start));
 }

}</source>





Using arraycopy().

   <source lang="java">

class ACDemo {

 static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
 static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 };
 public static void main(String args[]) {
   System.out.println("a = " + new String(a));
   System.out.println("b = " + new String(b));
   System.arraycopy(a, 0, b, 0, a.length);
   System.out.println("a = " + new String(a));
   System.out.println("b = " + new String(b));
   System.arraycopy(a, 0, a, 1, a.length - 1);
   System.arraycopy(b, 1, b, 0, b.length - 1);
   System.out.println("a = " + new String(a));
   System.out.println("b = " + new String(b));
 }

}</source>





Wait until notepad is terminated.

   <source lang="java">

class ExecDemoFini {

 public static void main(String args[]) {
   Runtime r = Runtime.getRuntime();
   Process p = null;
   try {
     p = r.exec("notepad");
     p.waitFor();
   } catch (Exception e) {
     System.out.println("Error executing notepad.");
   }
   System.out.println("Notepad returned " + p.exitValue());
 }

}</source>