当应用程序被正常关闭时,程序将首先开启任何注册了的关闭线程,等它们结束后才真正退出.
// 注册一个关闭线程
Runtime.getRuntime().addShutdownHook(new Thread() {
// This method is called during shutdown
public void run() {
// Do shutdown work ...
}
});
计算耗费的时间
// 取得当前时间 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);
完成一个能被排序的类
In order for a class to be used in a sorted collection such as a
SortedTree or for it to be sortable by Collections.sort(), the class must implement Comparable. 为了让一个类能用于如
SortedTree 这样的可[排序集合中,或是让它能被Collections.sort()函数排序,类必须实现Comparable接口.
public class MyClass implements Comparable {
public int compareTo(Object o) {
// If this < o, return a negative value
// If this = o, return 0
// If this > o, return a positive value
}
}
重定向标准输出及错误(在跟踪调试程序时也许能有妙用)
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");
加载一个不在classpath中的类
A URLClassLoader can be used to load classes in any directory.
URLClassLoader 可以用于加载位于其它目录的类
// 创建一个包括类文件的目录的File对象 Create a File object on the root of the directory containing the class file
File file = new File("c:\myclasses\");
try {
// 将File转化为URL Convert File to a URL
URL url = file.toURL(); // file:/c:/myclasses/
URL[] urls = new URL[]{url};
// 使用目录创建一个新的ClassLoader 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) {
}
执行一条命令行命令
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) {
}
// 如果参数包括空格,必须用数组来包含参数
try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}
读取命令的输出
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) {
}
向命令输入
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) {
}
