haofenglemon 发表于 2013-1-25 22:17:31

java 常用的代码

收集的java常用代码,共同分享(二)
Java code
/**
* (#)ThrowableManager.java    1.0    Apr 10, 2008
*
* Copyright 2007- wargrey , Inc. All rights are reserved.
*/
package net.wargrey.application;

import java.awt.Component;
import javax.swing.JOptionPane;

/**
* This class <code>ExceptionManager</code> and its subclasses are a form of
* <code>Exception</code>. It is used to wrap all the <code>Throwable</code> instances
* and handle them in a unified way. It will show the information which consists of
* StackTraces and Messages by using JOptionPanel.
*
* @author Estelle
* @version 1.0
* @see java.lang.Exception
* @since jdk 1.5
*/
public class ExceptionManager extends Exception {
   
    /**
   * This field <code>alerter</code> is used to show the information the Class offered.
   *
   * @see javax.swing.JOptionPane
   */
    private JOptionPane alerter;
   
    /**
   * This static method create an instance of the ExceptionManager by invoking the
   * constructor <code>ExceptionManager(String msg)</code>.
   *
   * @param msg    The message will pass the specified constructor
   * @return    An instance of the ExceptionManager created by invoking the constructor
   *             <code>ExceptionManager(String msg)</code>.
   */
    public static ExceptionManager wrap(String msg){
      return new ExceptionManager(msg);
    }
   
    /**
   * This static method create an instance of the ExceptionManager by invoking the
   * constructor <code>ExceptionManager(Throwable throwable)</code>.
   *
   * @param throwable      The cause will pass the specified constructor
   * @return    An instance of the ExceptionManager created by invoking the constructor
   *             <code>ExceptionManager(Throwable throwable)</code>.
   */
    public static ExceptionManager wrap(Throwable throwable){
      return new ExceptionManager(throwable);
    }
   
    /**
   * This static method create an instance of the ExceptionManager by invoking the
   * constructor <code>ExceptionManager(String msg,Throwable throwable)</code>.
   *
   * @param msg            The message will pass the specified constructor
   * @param throwable      The cause will pass the specified constructor
   * @return    An instance of the ExceptionManager created by invoking the constructor
   *             <code>ExceptionManager(String msg, Throwable throwable)</code>
   */
    public static ExceptionManager wrap(String msg,Throwable throwable){
      return new ExceptionManager(msg,throwable);
    }
   
    /**
   * Constructs a new instance with the specified detail message. The concrete handler
   * is its super class. This constructor always used to construct a custom exception
   * not wrapping the exist exception.
   *
   * @param msg      the detail message which is the part of the information will be
   *                     shown.
   */
    public ExceptionManager(String msg){
      super(msg);
    }
   
    /**
   * Constructs a new instance with the specified detail cause. The concrete handler
   * is its super class. This constructor always used to wrap an exist exception.
   *
   * @param throwable      the cause which has been caught. It's detail message and
   *                         stacktrace are the parts the information will be shown.
   */
    public ExceptionManager(Throwable throwable){
      super(throwable);
    }
   
    /**
   * Constructs a new instance with the specified detail message and cause. The
   * concrete handler is its super class. This constructor always used to construct
   * an exception wrapping the exist exception but requires a custom message.
   *
   * @param msg      the detail message which is the part of the information will
   *                     be shown.
   * @param throwable    the cause which has been caught. It's stacktrace is the parts
   *                     the information will be shown.
   */
    public ExceptionManager(String msg,Throwable throwable){
      super(msg,throwable);
    }
   
    /**
   * Show the information with everything is default.
   */
    public synchronized void alert(){
      alert((Component)null);
    }
   
    /**
   * Show the information in a dialog with the specified title
   * "ThrowableManager Alerter". The dialog belongs to the given component which
   * default is the screen.
   *
   * @param parent    The component cause the exception.
   */
    public synchronized void alert(Component parent){
      alert(parent,"ThrowableManager Alerter");
    }
   
    /**
   * Show the information in a dialog with the specified title.
   *
   * @param title      The title of the dialog.
   */
    public synchronized void alert(String title){
      alert((Component)null,title);
    }
   
    /**
   * Show the information in a dialog which has the specified title and belongs to the
   * specified component.
   *
   * @param parent    The component cause the exception.
   * @param title      The title of the dialog.
   */
    public synchronized void alert(Component parent,String title){
      StringBuilder errorMessage=new StringBuilder();
      errorMessage.append(this.toString());
      for (StackTraceElement st:((this.getCause()==null)?this:this.getCause()).getStackTrace()){
            errorMessage.append("\n\t   at ");
            errorMessage.append(st.toString());
      }      
      alerter.showMessageDialog(parent, errorMessage, title ,JOptionPane.ERROR_MESSAGE);
    }
}Java code
基础的java事件练习代码
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class ToolTipCtrl
{
    private static boolean flag = true;
   
    public static void main(String[] args)
    {
      JFrame frame = new JFrame();
      final JButton btnSH = new JButton("Show or Hide");
      final JButton btnS = new JButton("Show Only");
      
      btnSH.setToolTipText(btnSH.getText());
      btnS.setToolTipText(btnS.getText());
      frame.add(btnSH, BorderLayout.WEST);
      frame.add(btnS, BorderLayout.EAST);
      
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(300, 100);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      
      btnSH.addActionListener(new ActionListener()
      {
            public void actionPerformed(ActionEvent e)
            {
                if(flag)
                {
                  postToolTip(btnSH);
                }
                else
                {
                  hideToolTip(btnSH);
                }
               
                flag = !flag;
            }
      });
      
      btnS.addActionListener(new ActionListener()
      {
            public void actionPerformed(ActionEvent e)
            {
                postToolTip(btnS);
            }
      });
    }

    public static void postToolTip(JComponent comp)
    {
      Action action = comp.getActionMap().get("postTip");
      
      if(action != null)
      {
            ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, "postTip", EventQueue.getMostRecentEventTime(), 0);
            action.actionPerformed(ae);
      }
    }

    public static void hideToolTip(JComponent comp)
    {
      Action action = comp.getActionMap().get("hideTip");
      
      if(action != null)
      {
            ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, "hideTip", EventQueue.getMostRecentEventTime(), 0);
            action.actionPerformed(ae);
      }
    }
}
一些公共函数


Java code

//过滤特殊字符
public static String encoding(String src){
      if (src==null)
            return "";
      StringBuilder result=new StringBuilder();
      if (src!=null){
            src=src.trim();
            for (int pos=0;pos<src.length();pos++){
                switch(src.charAt(pos)){
                  case '\"':result.append(""");break;
                  case '<':result.append("<");break;
                  case '>':result.append(">");break;
                  case '\'':result.append("'");break;
                  case '&':result.append("&");break;
                  case '%':result.append("&pc;");break;
                  case '_':result.append("&ul;");break;
                  case '#':result.append("&shap;");break;
                  case '?':result.append("&ques;");break;
                  default:result.append(src.charAt(pos));break;
                }
            }
      }
      return result.toString();
    }
   
//反过滤特殊字符
    public static String decoding(String src){
      if (src==null)
            return "";
      String result=src;
      result=result.replace(""", "\"").replace("'", "\'");
      result=result.replace("<", "<").replace(">", ">");
      result=result.replace("&", "&");
      result=result.replace("&pc;", "%").replace("&ul", "_");
      result=result.replace("&shap;", "#").replace("&ques", "?");
      return result;
    }

//利用反射调用一个继承层次上的函数族,比如安装程序,有安装数据库的,安装文件系统的等,命名均已“install”开始,你就可以将参数part设为“install”,src是其实类实例,root是终止父类
    public static <T> void invokeMethods(String part,T src,Class root) throws ExceptionManager{
      if (root!=null){
            if (!root.isInstance(src))return;
            root=(Class)root.getGenericSuperclass();
      }
      HashMap<String,Method> invokees=new HashMap<String,Method>();
      Class target=src.getClass();
      do{
            Method [] methods=target.getDeclaredMethods();
            for (Method method:methods){
                String mn=method.getName();
                Boolean isPass=mn.startsWith(part);
                if (isPass){
                  Integer nopt=method.getParameterTypes().length;
                  Boolean isStatic=Modifier.isStatic(method.getModifiers());
                  if ((nopt==0)&&(!isStatic)){
                        if (!invokees.containsKey(mn))
                            invokees.put(mn, method);
                  }
                }
            }
            target=(Class)target.getGenericSuperclass();
      }while(target!=root);
      Iterator<String> methods=invokees.keySet().iterator();
      while (methods.hasNext()){
            Method invokee=invokees.get(methods.next());
            Boolean access=invokee.isAccessible();
            invokee.setAccessible(true);
            try {
                invokee.invoke(src);
            } catch (InvocationTargetException e) {
                throw ExceptionManager.wrap(e.getTargetException());
            }catch (Exception e){}
            invokee.setAccessible(access);
      }
    }收藏的数据库联接,csdn上的
Java code
MySQL:   
    String Driver="com.mysql.jdbc.Driver";    //驱动程序
    String URL="jdbc:mysql://localhost:3306/db_name";    //连接的URL,db_name为数据库名   
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).new Instance();
    Connection con=DriverManager.getConnection(URL,Username,Password);
Microsoft SQL Server 2.0驱动(3个jar的那个):
    String Driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";    //连接SQL数据库的方法
    String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";    //db_name为数据库名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).new Instance();    //加载数据可驱动
    Connection con=DriverManager.getConnection(URL,UserName,Password);    //
Microsoft SQL Server 3.0驱动(1个jar的那个): // 老紫竹完善
    String Driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";    //连接SQL数据库的方法
    String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name";    //db_name为数据库名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).new Instance();    //加载数据可驱动
    Connection con=DriverManager.getConnection(URL,UserName,Password);    //
Sysbase:
    String Driver="com.sybase.jdbc.SybDriver";    //驱动程序
    String URL="jdbc:Sysbase://localhost:5007/db_name";    //db_name为数据可名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();   
    Connection con=DriverManager.getConnection(URL,Username,Password);
Oracle(用thin模式):
    String Driver="oracle.jdbc.driver.OracleDriver";    //连接数据库的方法
    String URL="jdbc:oracle:thin:@loaclhost:1521:orcl";    //orcl为数据库的SID
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();    //加载数据库驱动
    Connection con=DriverManager.getConnection(URL,Username,Password);   
PostgreSQL:
    String Driver="org.postgresql.Driver";    //连接数据库的方法
    String URL="jdbc:postgresql://localhost/db_name";    //db_name为数据可名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();   
    Connection con=DriverManager.getConnection(URL,Username,Password);
DB2:
    String Driver="com.ibm.db2.jdbc.app.DB2.Driver";    //连接具有DB2客户端的Provider实例
    //String Driver="com.ibm.db2.jdbc.net.DB2.Driver";    //连接不具有DB2客户端的Provider实例
    String URL="jdbc:db2://localhost:5000/db_name";    //db_name为数据可名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();   
    Connection con=DriverManager.getConnection(URL,Username,Password);
Informix:
    String Driver="com.informix.jdbc.IfxDriver";   
    String URL="jdbc:Informix-sqli://localhost:1533/db_name:INFORMIXSER=myserver";    //db_name为数据可名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();   
    Connection con=DriverManager.getConnection(URL,Username,Password);
JDBC-ODBC:
    String Driver="sun.jdbc.odbc.JdbcOdbcDriver";
    String URL="jdbc:odbc:dbsource";    //dbsource为数据源名
    String Username="username";    //用户名
    String Password="password";    //密码
    Class.forName(Driver).newInstance();   
    Connection con=DriverManager.getConnection(URL,Username,Password);控制小数点的几个常用方法: Java code

import java.text.DecimalFormat;

public class NumberUtil {
   
    public static double decimalFormatD(int num, double d){
      String format = "0.";
      String result = "";
      double db;
      
      for(int i=0;i<num;i++)
            format = format.concat("0");
      
      DecimalFormat decimal = new DecimalFormat(format);
      result = decimal.format(d);
      db = Double.parseDouble(result);
      
      return db;
    }
   
    public static float decimalFormatF(int num, float f){
      String format = "0.";
      String result = "";
      float fl;
      
      for(int i=0;i<num;i++)
            format = format.concat("0");
      
      DecimalFormat decimal = new DecimalFormat(format);
      result = decimal.format(f);
      fl = Float.parseFloat(result);
      
      return fl;
    }

   
    public static String doubleToString(double f){      
      String s = "";
      double a = 0;
      
      while(f >= 1) {
            
            a = f%((double)10);
            
            s = String.valueOf((int)a) + s;
            f=(f - a)/10;
      }
      return s;
    }
}


用一个for循环打印九九乘法表 Java code
   /**
    *一个for循环打印九九乘法表
    */
    public void nineNineMultiTable()
    {
      for (int i = 1,j = 1; j <= 9; i++) {
          System.out.print(i+"*"+j+"="+i*j+" ");
          if(i==j)
          {
            i=0;
            j++;
            System.out.println();
          }
      }
    }

jdbc连接sql server Java code
package util;

import java.sql.*;

public class JdbcUtil
{
    public static void close(Statement st, Connection con)
    {
      try
      {
            st.close();
      }catch(Exception e)
      {
      }
      
      try
      {
            con.close();
      }catch(Exception e)
      {
      }
    }
   
    public static void close(ResultSet rs, Statement st, Connection con)
    {
      try
      {
            rs.close();
      }catch(Exception e)
      {
      }
      close(st, con);
    }
   
    public static Connection getConnection() throws Exception
    {
      Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
      return DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db", "sa", "54321");

    }
}

简单的txt转换xml Java code
package com.liu;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;

public class TxtToXml {
private String strTxtFileName;

private String strXmlFileName;

public TxtToXml() {
strTxtFileName = new String();
strXmlFileName = new String();
}

public void createXml(String strTxt, String strXml) {
strTxtFileName = strTxt;
strXmlFileName = strXml;
String strTmp;
try {
   BufferedReader inTxt = new BufferedReader(new FileReader(
   strTxtFileName));
   BufferedWriter outXml = new BufferedWriter(new FileWriter(
   strXmlFileName));
   outXml.write("<?xml version= \"1.0\" encoding=\"gb2312\"?>");
   outXml.newLine();
   outXml.write("<people>");
   while ((strTmp = inTxt.readLine()) != null) {
    StringTokenizer strToken = new StringTokenizer(strTmp, ",");
    String arrTmp[];
    arrTmp = new String;
    for (int i = 0; i < 3; i++)
   arrTmp = new String("");
    int index = 0;
    outXml.newLine();
    outXml.write("    <students>");
    while (strToken.hasMoreElements()) {
   strTmp = (String) strToken.nextElement();
   strTmp = strTmp.trim();
   arrTmp = strTmp;
    }
    outXml.newLine();
    outXml.write("      <name>" + arrTmp + "</name>");
    outXml.newLine();
    outXml.write("      <sex>" + arrTmp + "</sex>");
    outXml.newLine();
    outXml.write("      <age>" + arrTmp + "</age>");
    outXml.newLine();
    outXml.write("    </students>");
   }
   outXml.newLine();
   outXml.write("</people>");
   outXml.flush();
} catch (Exception e) {
   e.printStackTrace();
}
}
public static void main(String[] args) {
String txtName = "testtxt.txt";
String xmlName = "testxml.xml";
TxtToXml thisClass = new TxtToXml();
thisClass.createXml(txtName, xmlName);
}
}
页: [1]
查看完整版本: java 常用的代码