Java Tutorial/Development/Runtime System — различия между версиями

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

Текущая версия на 15:28, 31 мая 2010

Demonstrate exec().

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





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

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





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





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

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





Display the maximum amount of memory

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





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

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





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





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





Milliseconds elapsed since January 1, 1970

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





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





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





System.getProperty

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





Timing program execution.

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





Using arraycopy().

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





Wait until notepad is terminated.

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