为Java程序添加退出事件

Posted on 2006-01-21 15:28 caid'weblog 阅读(960) 评论(0)  编辑  收藏 所属分类: JAVA

package org.swing.os;

import java.util.*;
import java.io.*;

/**
 * 为Java程序添加退出事件
 *
 * @author wuhq
 */
public class ExitEventJavaApp {

 public ExitEventJavaApp() {
  doShutDownWork();
 }

 private void doShutDownWork() {
  Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() {
    try {
     FileWriter fw = new FileWriter("d:\\t.log");
     System.out.println("即将关闭");
     fw.write("Bye " + (new Date()).toString());
     fw.flush();
     fw.close();
    } catch (IOException ex) {
    }
   }
  });
 }

 public static void main(String[] args) {
  new ExitEventJavaApp();
  long start = System.currentTimeMillis();
  for (int i = 0; i < 100; i++) {
   try {
    FileOutputStream fos = new FileOutputStream(new File(
      "d:\\test.txt"), true);
    fos.write("你好啊!\n".getBytes());
    fos.close();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  long end = System.currentTimeMillis();
  System.out.println(end - start);
 }
}


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 5, comments - 4, trackbacks - 0, articles - 3

Copyright © caid'weblog