Java Application and System
Terminating the Application
// No errors
int errorCode = 0;
// An error occurred
errorCode = -1;
// Terminate
System.exit(errorCode);
System Properties
Getting and Setting the Value of a System Property
// Get a system property
String dir = System.getProperty("user.dir");
// Set a system property
String previousValue = System.setProperty("application.property", "newValue");
Setting the Value of a System Property from the Command Line
A system property can be set or overridden by specifying the -D option to the java command when running your program.
java -Dmy.prop="my value" MyApp
// Get the value of the system property
String prop = System.getProperty("my.prop");
// my value
Listing All System Properties
// Get all system properties
Properties props = System.getProperties();
// Enumerate all system properties
Enumeration enum = props.propertyNames();
for (; enum.hasMoreElements(); ) {
// Get property name
String propName = (String)enum.nextElement();
// Get property value
String propValue = (String)props.get(propName);
}
Loading Native Code
On Windows, loadLibrary("s") loads s.dll. On Solaris, it loads s.so.
System.loadLibrary("libraryName");
Computing Elapsed Time
// Get current time
long start = System.currentTimeMillis();
// Do something ...
// Get elapsed time in milliseconds
long elapsedTimeMillis = System.currentTimeMillis()-start;
// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;
// Get elapsed time in minutes
float elapsedTimeMin = elapsedTimeMillis/(60*1000F);
// Get elapsed time in hours
float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);
// Get elapsed time in days
float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);
Redirecting Standard Output, and Error
This example replaces standard output and error with a print stream that copies its output to both the console and to a file.
// All writes to this print stream are copied to two print streams
public class TeeStream extends PrintStream {
PrintStream out;
public TeeStream(PrintStream out1, PrintStream out2) {
super(out1);
this.out = out2;
}
public void write(byte buf[], int off, int len) {
try {
super.write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
super.flush();
out.flush();
}
}
Here's an example that uses the class:
try {
// Tee standard output
PrintStream out = new PrintStream(new FileOutputStream("out.log"));
PrintStream tee = new TeeStream(System.out, out);
System.setOut(tee);
// Tee standard error
PrintStream err = new PrintStream(new FileOutputStream("err.log"));
tee = new TeeStream(System.err, err);
System.setErr(tee);
} catch (FileNotFoundException e) {
}
// Write to standard output and error and the log files
System.out.println("welcome");
System.err.println("error");
Getting the Size of the Java Memory Heap
The heap is the area in memory in which objects are created.
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
Classloaders and Classpath
Determining from Where a Class Was Loaded
// Get the location of this class
Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation(); // file:/c:/almanac14/examples/
It is not possible to determine the location of classes loaded by the system class loader in the same way since the class' code source is null. The only other method is to use the -verbose option on the java command. This causes the Java virtual machine to print a message every time a class is loaded.
> java -verbose MyApp
Here's a sample of the output:
[Opened c:\jdk1.4\jre\lib\rt.jar]
[Opened c:\jdk1.4\jre\lib\sunrsasign.jar]
[Opened c:\jdk1.4\jre\lib\jsse.jar]
[Opened c:\jdk1.4\jre\lib\jce.jar]
[Opened c:\jdk1.4\jre\lib\charsets.jar]
[Loaded java.lang.Object from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.io.Serializable from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.Comparable from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.CharSequence from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.String from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.Class from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.Cloneable from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.ClassLoader from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.System from c:\jdk1.4\jre\lib\rt.jar]
[Loaded java.lang.Throwable from c:\jdk1.4\jre\lib\rt.jar]
Loading a Class That Is Not on the Classpath
A URLClassLoader can be used to load classes in any directory.
// Create a File object on the root of the directory containing the class file
File file = new File("c:\\myclasses\\");
try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/myclasses/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
Class cls = cl.loadClass("com.mycompany.MyClass");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}
Dynamically Reloading a Modified Class
This example demonstrates how to reload a modified class without restarting the application. The technique involves loading the reloadable class with a separate class loader. Each time the class needs to be reloaded, it is loaded using a new class loader and the previous class loader (with the old class) is abandoned.
It is important that the reloadable class not be on the classpath. Otherwise, the class will be loaded by some parent of the new class loader rather than by the new class loader itself. Once this happens, the class cannot be reloaded.
Since the class cannot be on the classpath, it is not possible to use the class name directly in the code (otherwise a ClassNotFoundException would be thrown during start up). To circumvent this problem, the reloadable class must be made to implement an interface and the interface name is used in the code. This example places the reloadable class in a subdirectory called dir, which is not on the classpath. Here is the reloadable class:
public class MyReloadableClassImpl implements MyReloadableClass {
public String myMethod() {
return "a message";
}
}
To compile this class, it is necessary to tell the compiler the location of MyReloadableClass. Since, for this example, it is located in the parent directory, the following command will compile this class:
> java -classpath .. MyReloadableClass
Here's the code that reloads the reloadable class:
// Get the directory (URL) of the reloadable class
URL[] urls = null;
try {
// Convert the file object to a URL
File dir = new File(System.getProperty("user.dir")
+File.separator+"dir"+File.separator);
URL url = dir.toURL(); // file:/c:/almanac1.4/examples/
urls = new URL[]{url};
} catch (MalformedURLException e) {
}
try {
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class
Class cls = cl.loadClass("MyReloadableClassImpl");
// Create a new instance of the new class
myObj = (MyReloadableClass)cls.newInstance();
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
}
Here's some code that tests the reloadable class (a more realistic routine would periodically check the timestamp on the file). After the example is started, change the string returned by myMethod() and recompile.
try {
while (true) {
reloadMyReloadedClass();
System.out.println(myObj.myMethod());
Thread.sleep(5000);
}
} catch (Exception e) {
}
Commands
Executing a Command
try {
// 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);
} catch (IOException e) {
}
If an argument contain spaces, it is necessary to use the overload that requires the command and its arguments to be supplied in an array:
try {
// 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:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}
Reading Output from a Command
try {
// Execute command
String command = "ls";
Process child = Runtime.getRuntime().exec(command);
// Get the input stream and read from it
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1) {
process((char)c);
}
in.close();
} catch (IOException e) {
}
Sending Input to a Command
try {
// Execute command
String command = "cat";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("some text".getBytes());
out.close();
} catch (IOException e) {
}
How to convert a Collection of objects to an ArrayList:
Say you have a collection called customers:
Collection customers=GetCustomers();
How to initialize static (class) members in Java
(1) Using Static Initialization Blocks
Here's an example of a static initialization block:
import java.util.*;
class Errors {
static ResourceBundle errorStrings;
static {
try {
errorStrings =
ResourceBundle.getBundle("ErrorStrings");
} catch (MissingResourceException e) {
//error recovery code here
}
}
}
A static initialization block begins with the static keyword and is a normal block of code enclosed in braces: { and }. The errorStrings resource bundle must be initialized in a static initialization block because the getBundle method can throw an exception if the bundle cannot be found. The code should perform error recovery. Also, errorStrings is a class member, so it should not be initialized in a constructor.
A class can have any number of static initialization blocks that appear anywhere in the class body. The runtime system guarantees that static initialization blocks and static initializers are called in the order (left to right, top to bottom) that they appear in the source code.
(2) write a private static method:
There is an alternative to static blocks — write a private static method:
import java.util.*;
class Errors {
static ResourceBundle errorStrings = initErrorStrings();
private static ResourceBundle initErrorStrings() {
try {
return ResourceBundle.getBundle("ErrorStrings");
} catch (MissingResourceException e) {
//error recovery code here
}
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class. In this example, that could be useful if a new translation is installed.
Ref: http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html