`
haofenglemon
  • 浏览: 244022 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java 常用的代码

    博客分类:
  • user
阅读更多
收集的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("&quot;");break;
                    case '<':result.append("&lt;");break;
                    case '>':result.append("&gt;");break;
                    case '\'':result.append("&apos;");break;
                    case '&':result.append("&amp;");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("&quot;", "\"").replace("&apos;", "\'");
        result=result.replace("&lt;", "<").replace("&gt;", ">");
        result=result.replace("&amp;", "&");
        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[3];
    for (int i = 0; i < 3; i++)
     arrTmp[i] = new String("");
    int index = 0;
    outXml.newLine();
    outXml.write("    <students>");
    while (strToken.hasMoreElements()) {
     strTmp = (String) strToken.nextElement();
     strTmp = strTmp.trim();
     arrTmp[index++] = strTmp;
    }
    outXml.newLine();
    outXml.write("        <name>" + arrTmp[0] + "</name>");
    outXml.newLine();
    outXml.write("        <sex>" + arrTmp[1] + "</sex>");
    outXml.newLine();
    outXml.write("        <age>" + arrTmp[2] + "</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);
}
}
分享到:
评论

相关推荐

    java常用代码

    本压缩包“java常用代码”集合了一系列基础到进阶的Java代码示例,涵盖了多个关键领域,有助于初学者快速掌握Java编程的核心概念。 1. **遗产算法**:在Java中,继承是面向对象特性之一,它允许一个类(子类)继承...

    java常用代码的集合

    以下是对标题“java常用代码的集合”和描述中提及的知识点的详细解释,以及与标签相关的具体代码示例。 1. ISBN验证: ISBN(国际标准书号)是用于唯一标识书籍的编码。在Java中,我们可以编写一个方法来验证一个...

    Java常用代码方法汇总

    java常用代码方法很适合初学者和刚刚参加工作的程序员,里面包含了常用正则表达式、公共日期类、串口驱动、各种数据库连接、公交换乘算法、 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤等等很多有用的...

    JAVA常用代码块

    JAVA常用代码块 JAVA常用代码块 JAVA常用代码块 JAVA常用代码块 JAVA常用代码块

    Java常用代码整理

    在"Java常用代码整理"这个主题中,我们可以探讨多个Java编程中的关键知识点,包括基础语法、面向对象特性、异常处理、集合框架、IO流、多线程、网络编程以及实用工具类等。 1. **基础语法**:Java的基础语法包括...

    Java常用代码

    为了更好地理解如何使用Java代码解析XML文件,下面给出一个简单的XML示例文档: ```xml &lt;code&gt;100001 &lt;pass&gt;123 李四 &lt;money&gt;1000000.00 &lt;code&gt;100002 &lt;pass&gt;123 张三 &lt;money&gt;500000.00 ``` ...

    Java常用代码大全.zip

    "Java常用代码大全.zip"这个压缩包很可能包含了各种常见的Java编程示例和实用代码片段,帮助开发者快速解决日常开发中遇到的问题。这个文档,"Java常用代码大全.doc",可能是一个详细的指南,涵盖了Java开发中的各种...

    Java常用代码全集.7z

    "Java常用代码全集.7z"这个压缩包文件很可能是收集了一系列Java编程中的常见代码示例,旨在帮助开发者快速理解和学习各种Java编程技巧。这个文件包含了"Java常用代码全集.doc"文档,这可能是一个详细的代码库,覆盖...

    Java常用代码全集.zip

    "Java常用代码全集.zip"这个压缩包文件很可能包含了一整套实用的Java代码示例,旨在帮助开发者更好地理解和掌握Java编程的核心概念、语法以及常见问题的解决方案。 文档"Java常用代码全集.doc"可能涵盖了以下几个...

    java常用代码工具包

    "java常用代码工具包"通常包含了一系列预编写、经过优化的代码片段或类库,旨在简化开发过程,提高效率。这个工具包可能是个人或社区开发者的经验结晶,包含了他们在实际开发中经常用到的功能模块。 1. **基础工具...

    java常用代码,常用的如数据库连接等

    在"java常用代码,常用的如数据库连接等"这个主题中,我们可以深入探讨几个关键的知识点,包括Java基础、异常处理、集合框架以及数据库连接。 1. **Java基础**:Java的基础包括语法、数据类型、变量、运算符、流程...

    JAVA 常用代码 Eclipse快捷键大全

    下面将详细讲解标题和描述中提到的"JAVA常用代码"与"Eclipse快捷键大全"的相关知识点。 首先,让我们探讨"JAVA常用代码"。Java是一种广泛使用的面向对象的编程语言,其语法简洁且强大。以下是一些Java开发者经常...

    Java常用代码和方法

    本资源"Java常用代码和方法"提供了一系列的示例和详细注释,旨在帮助初学者更好地理解和运用Java的核心概念。以下是一些关键的知识点,它们通常会在Java开发中频繁出现: 1. **基础数据类型与封装类**: Java提供...

    很实用的java常用代码

    "很实用的Java常用代码"这个压缩包文件显然包含了大量在日常开发中经常用到的代码片段,旨在帮助开发者提高效率,解决常见问题。下面,我们将详细探讨一些Java编程中的关键知识点。 1. 类与对象:Java是面向对象的...

Global site tag (gtag.js) - Google Analytics