整理java代码常见应用

 

java访问xml文件

Java code

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmljava
{

public static void main(String args[])
    {   
          Element element=null;
          File f =new File("a.xml");
          DocumentBuilder db=null;        //documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
          DocumentBuilderFactory dbf=null;
      try{
        
          dbf= DocumentBuilderFactory.newInstance(); //返回documentBuilderFactory对象 
          db =dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象

          Document dt= db.parse(f); //得到一个DOM并返回给document对象
          element = dt.getDocumentElement();//得到一个elment根元素
         
          System.out.println("根元素:"+element.getNodeName()); //获得根节点

        NodeList childNodes =element.getChildNodes() ;    // 获得根元素下的子节点
   
      for (int i = 0; i < childNodes.getLength(); i++)     // 遍历这些子节点

   {      
       Node node1 = childNodes.item(i); // childNodes.item(i); 获得每个对应位置i的结点

     if ("Account".equals(node1.getNodeName()))
      {
                        // 如果节点的名称为"Account",则输出Account元素属性type
      System.out.println("\r\n找到一篇账号. 所属区域: "   + node1.getAttributes().getNamedItem        ("type").getNodeValue() + ". ");
      NodeList nodeDetail = node1.getChildNodes();   // 获得<Accounts>下的节点
      for (int j = 0; j < nodeDetail.getLength(); j++)
       {   // 遍历<Accounts>下的节点
          Node detail = nodeDetail.item(j);    // 获得<Accounts>元素每一个节点
            if ("code".equals(detail.getNodeName()))   // 输出code
            System.out.println("卡号: " + detail.getTextContent());
             else if ("pass".equals(detail.getNodeName())) // 输出pass
                System.out.println("密码: " + detail.getTextContent());
             else if ("name".equals(detail.getNodeName())) // 输出name
                System.out.println("姓名: " + detail.getTextContent());
             else if ("money".equals(detail.getNodeName())) // 输出money
                 System.out.println("余额: "+ detail.getTextContent());
     
        }
      }

    }
}

catch(Exception e){System.out.println(e);}
   
}
}

XML code
<?xml version="1.0" encoding="gbk"?>     
<Accounts>
<Account type="by0003">
<code>100001</code>
<pass>123</pass>
<name>李四</name>
<money>1000000.00</money>
</Account>
<Account type="hz0001">
<code>100002</code>
<pass>123</pass>
<name>张三</name>
<money>1000.00</money>
</Account>
</Accounts>

 

java jdbc数据库连接

Java code

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JDBConnection {
    public Connection conn = null; // 声明Connection对象的实例
    public Statement stmt = null; // 声明Statement对象的实例
    public ResultSet rs = null; // 声明ResultSet对象的实例
   
    private static String dbClassName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";//定义保存数据库驱动的变量
    private static String dbUrl = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DB_ATM";
    private static String dbUser = "sa";
    private static String dbPwd = "sa";

    public JDBConnection(String propertyFileName) {// 带属性文件名的构造方法
        Properties prop = new Properties();// 属性集合对象
        InputStream is = null;
        try {
            is = JDBConnection.class.getClassLoader().getResourceAsStream(
                    propertyFileName);// 属性文件输入流
            // is = new FileInputStream("src/" + propertyFileName);
            prop.load(is);// 将属性文件流装载到Properties对象中
            is.close();// 关闭流
            dbClassName = prop.getProperty("dbClassName");
            dbUrl = prop.getProperty("dbUrl");
            dbUser = prop.getProperty("dbUser");
            dbPwd = prop.getProperty("dbPwd");
        } catch (Exception e) {
            System.out.println("属性文件  " + propertyFileName + " 打开失败!");
        }
        try {

            Class.forName(dbClassName);// 1.注册驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public JDBConnection() {// 默认的不带参数的构造函数
        try {

            Class.forName(dbClassName);// 1.注册驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            // Class.forName(dbClassName);// 1.注册驱动
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接
        } catch (Exception ee) {
            ee.printStackTrace();
        }
        if (conn == null) {
            System.err
                    .println("警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:"
                            + dbClassName
                            + "\r\n链接位置:"
                            + dbUrl
                            + "\r\n用户/密码"
                            + dbUser + "/" + dbPwd);
        }
        return conn;
    }

    /*
     * 功能:执行查询语句
     */
    public ResultSet executeQuery(String sql) {
        try { // 捕捉异常
            conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,//3.创建语句
                    ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);//4.执行查询
        } catch (SQLException ex) {
            System.err.println(ex.getMessage()); // 输出异常信息
        }
        return rs; // 返回结果集对象 5.结果处理
    }

    /*
     * 功能:执行更新操作
     */
    public int executeUpdate(String sql) {
        int result = 0; // 定义保存返回值的变量
        try { // 捕捉异常
            conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            result = stmt.executeUpdate(sql); // 执行更新操作
        } catch (SQLException ex) {
            result = 0; // 将保存返回值的变量赋值为0
        }
        return result; // 返回保存返回值的变量
    }

    /*
     * 功能:关闭数据库的连接
     */
    public void close() {//6.释放资源
        try { // 捕捉异常
            try {
                if (rs != null) { // 当ResultSet对象的实例rs不为空时
                    rs.close(); // 关闭ResultSet对象
                }
            } finally {
                try {
                    if (stmt != null) { // 当Statement对象的实例stmt不为空时
                        stmt.close(); // 关闭Statement对象
                    }
                } finally {
                    if (conn != null) { // 当Connection对象的实例conn不为空时
                        conn.close(); // 关闭Connection对象
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err); // 输出异常信息
        }
    }

}


属性文件
dbClassName=com.microsoft.jdbc.sqlserver.SQLServerDriver
dbClassName2=com.mysql.jdbc.Driver
dbPwd=sa
dbPwd2=root
dbUrl=jdbc\:microsoft\:sqlserver\://localhost\:1433;DatabaseName\=DB_ATM
dbUrl2=jdbc\:mysql\://localhost\:3306/db_atm
dbUser=sa
dbUser2=root


java访问资源文件

Java code
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.Properties;  
 
public class PropertyEditor {  
    public static void main(String[] args) throws Exception {  
        Properties prop = new Properties();// 属性集合对象  
        FileInputStream fis = new FileInputStream("prop.properties");// 属性文件输入流   (相对于根目录下的文件名,要加上包名 “src/prop.properties”)
        prop.load(fis);// 将属性文件流装载到Properties对象中  
        fis.close();// 关闭流  
 
        // 获取属性值,sitename已在文件中定义  
        System.out.println("获取属性值:sitename=" + prop.getProperty("sitename"));  
        // 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件  
        System.out.println("获取属性值:country=" + prop.getProperty("country", "中国")); 
 
        // 修改sitename的属性值  
        prop.setProperty("sitename", "中国");  
        // 添加一个新的属性studio  
        prop.setProperty("studio", "Boxcode Studio");  
        // 文件输出流  
        FileOutputStream fos = new FileOutputStream("prop.properties");  
        // 将Properties集合保存到流中  
        prop.store(fos, "Copyright (c) Boxcode Studio");  
        fos.close();// 关闭流  
    }  

资源文件

sitename=\u4E2D\u56FD
siteurl=www.abcjava.com  
studio=Boxcode Studio


 

java日期处理bean

Java code
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DateUtil {
    protected static Log logger = LogFactory.getLog(DateUtil.class);

    // 格式:年-月-日 小时:分钟:秒
    public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";

    // 格式:年-月-日 小时:分钟
    public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";

    // 格式:年月日 小时分钟秒
    public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";

    // 格式:年-月-日
    public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";

    // 格式:月-日
    public static final String SHORT_DATE_FORMAT = "MM-dd";

    // 格式:小时:分钟:秒
    public static final String LONG_TIME_FORMAT = "HH:mm:ss";

    //格式:年-月
    public static final String MONTG_DATE_FORMAT = "yyyy-MM";

    // 年的加减
    public static final int SUB_YEAR = Calendar.YEAR;

    // 月加减
    public static final int SUB_MONTH = Calendar.MONTH;

    // 天的加减
    public static final int SUB_DAY = Calendar.DATE;

    // 小时的加减
    public static final int SUB_HOUR = Calendar.HOUR;

    // 分钟的加减
    public static final int SUB_MINUTE = Calendar.MINUTE;

    // 秒的加减
    public static final int SUB_SECOND = Calendar.SECOND;

    static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四",
            "星期五", "星期六" };

    @SuppressWarnings("unused")
    private static final SimpleDateFormat timeFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    public DateUtil() {
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     */
    public static java.util.Date stringtoDate(String dateStr, String format) {
        Date d = null;
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr);
        } catch (Exception e) {
            // log.error(e);
            d = null;
        }
        return d;
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     */
    public static java.util.Date stringtoDate(String dateStr, String format,
            ParsePosition pos) {
        Date d = null;
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr, pos);
        } catch (Exception e) {
            d = null;
        }
        return d;
    }

    /**
     * 把日期转换为字符串
     */
    public static String dateToString(java.util.Date date, String format) {
        String result = "";
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            result = formater.format(date);
        } catch (Exception e) {
            // log.error(e);
        }
        return result;
    }

    /**
     * 获取当前时间的指定格式
     */
    public static String getCurrDate(String format) {
        return dateToString(new Date(), format);
    }

    public static String dateSub(int dateKind, String dateStr, int amount) {
        Date date = stringtoDate(dateStr, FORMAT_ONE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(dateKind, amount);
        return dateToString(calendar.getTime(), FORMAT_ONE);
    }

    /**
     * 两个日期相减
     * @return 相减得到的秒数
     */
    public static long timeSub(String firstTime, String secTime) {
        long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
        long second = stringtoDate(secTime, FORMAT_ONE).getTime();
        return (second - first) / 1000;
    }

    /**
     * 获得某月的天数
     */
    public static int getDaysOfMonth(String year, String month) {
        int days = 0;
        if (month.equals("1") || month.equals("3") || month.equals("5")
                || month.equals("7") || month.equals("8") || month.equals("10")
                || month.equals("12")) {
            days = 31;
        } else if (month.equals("4") || month.equals("6") || month.equals("9")
                || month.equals("11")) {
            days = 30;
        } else {
            if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
                    || Integer.parseInt(year) % 400 == 0) {
                days = 29;
            } else {
                days = 28;
            }
        }

        return days;
    }

    /**
     * 获取某年某月的天数
     */
    public static int getDaysOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获得当前日期
     */
    public static int getToday() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 获得当前月份
     */
    public static int getToMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获得当前年份
     */
    public static int getToYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的天
     */
    public static int getDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    /**
     * 返回日期的年
     */
    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的月份,1-12
     */
    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
     */
    public static long dayDiff(Date date1, Date date2) {
        return (date2.getTime() - date1.getTime()) / 86400000;
    }

    /**
     * 比较两个日期的年差
     */
    public static int yearDiff(String before, String after) {
        Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(afterDay) - getYear(beforeDay);
    }

    /**
     * 比较指定日期与当前日期的差
     */
    public static int yearDiffCurr(String after) {
        Date beforeDay = new Date();
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(beforeDay) - getYear(afterDay);
    }
   
    /**
     * 比较指定日期与当前日期的差
     */
    public static long dayDiffCurr(String before) {
        Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
        Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
        return (currDate.getTime() - beforeDate.getTime()) / 86400000;

    }

    /**
     * 获取每月的第一周
     */
    public static int getFirstWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, 1);
        return c.get(Calendar.DAY_OF_WEEK);
    }
    /**
     * 获取每月的最后一周
     */
    public static int getLastWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, getDaysOfMonth(year, month));
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss"
     *
     * @return
     */
    public static String getCurrent() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        StringBuffer sb = new StringBuffer();
        sb.append(year).append("_").append(StringUtil.addzero(month, 2))
                .append("_").append(StringUtil.addzero(day, 2)).append("_")
                .append(StringUtil.addzero(hour, 2)).append("_").append(
                        StringUtil.addzero(minute, 2)).append("_").append(
                        StringUtil.addzero(second, 2));
        return sb.toString();
    }

    /**
     * 获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss"
     *
     * @return
     */
    public static String getNow() {
        Calendar today = Calendar.getInstance();
        return dateToString(today.getTime(), FORMAT_ONE);
    }

  

    /**
     * 判断日期是否有效,包括闰年的情况
     *
     * @param date
     *          YYYY-mm-dd
     * @return
     */
    public static boolean isDate(String date) {
        StringBuffer reg = new StringBuffer(
                "^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
        reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
        reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
        reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
        reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
        reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
        Pattern p = Pattern.compile(reg.toString());
        return p.matcher(date).matches();
    }

 

点到线段的最短距离


Java code


private double pointToLine(int x1, int y1, int x2, int y2, int x0,
                int y0) {
            double space = 0;
            double a, b, c;
            a = lineSpace(x1, y1, x2, y2);// 线段的长度
            b = lineSpace(x1, y1, x0, y0);// (x1,y1)到点的距离
            c = lineSpace(x2, y2, x0, y0);// (x2,y2)到点的距离
            if (c <= 0.000001 || b <= 0.000001) {
                space = 0;
                return space;
            }
            if (a <= 0.000001) {
                space = b;
                return space;
            }
            if (c * c >= a * a + b * b) {
                space = b;
                return space;
            }
            if (b * b >= a * a + c * c) {
                space = c;
                return space;
            }
            double p = (a + b + c) / 2;// 半周长
            double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));// 海伦公式求面积
            space = 2 * s / a;// 返回点到线的距离(利用三角形面积公式求高)
            return space;
        }

        // 计算两点之间的距离
        private double lineSpace(int x1, int y1, int x2, int y2) {
            double lineLength = 0;
            lineLength = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
                    * (y1 - y2));
            return lineLength;

        }


 

java哈弗曼编码的实现

Java code


//哈弗曼编码的实现类
public class HffmanCoding {
    private int charsAndWeight[][];// [][0]是 字符,[][1]存放的是字符的权值(次数)
    private int hfmcoding[][];// 存放哈弗曼树
    private int i = 0;// 循环变量
    private String hcs[];

    public HffmanCoding(int[][] chars) {
        // TODO 构造方法
        charsAndWeight = new int[chars.length][2];
        charsAndWeight = chars;
        hfmcoding = new int[2 * chars.length - 1][4];// 为哈弗曼树分配空间
    }

    // 哈弗曼树的实现
    public void coding() {
        int n = charsAndWeight.length;
        if (n == 0)
            return;
        int m = 2 * n - 1;
        // 初始化哈弗曼树
        for (i = 0; i < n; i++) {
            hfmcoding[i][0] = charsAndWeight[i][1];// 初始化哈弗曼树的权值
            hfmcoding[i][1] = 0;// 初始化哈弗曼树的根节点
            hfmcoding[i][2] = 0;// 初始化哈弗曼树的左孩子
            hfmcoding[i][3] = 0;// 初始化哈弗曼树的右孩子
        }
        for (i = n; i < m; i++) {
            hfmcoding[i][0] = 0;// 初始化哈弗曼树的权值
            hfmcoding[i][1] = 0;// 初始化哈弗曼树的根节点
            hfmcoding[i][2] = 0;// 初始化哈弗曼树的左孩子
            hfmcoding[i][3] = 0;// 初始化哈弗曼树的右孩子
        }

        // 构建哈弗曼树
        for (i = n; i < m; i++) {
            int s1[] = select(i);// 在哈弗曼树中查找双亲为零的 weight最小的节点
            hfmcoding[s1[0]][1] = i;// 为哈弗曼树最小值付双亲
            hfmcoding[s1[1]][1] = i;
            hfmcoding[i][2] = s1[0];// 新节点的左孩子
            hfmcoding[i][3] = s1[1];// 新节点的右孩子
            hfmcoding[i][0] = hfmcoding[s1[0]][0] + hfmcoding[s1[1]][0];// 新节点的权值是左右孩子的权值之和
        }

    }

    // 查找双亲为零的 weight最小的节点
    private int[] select(int w) {
        // TODO Auto-generated method stub
        int s[] = { -1, -1 }, j = 0;// s1 最小权值且双亲为零的节点的序号 , i 是循环变量
        int min1 = 32767, min2 = 32767;
        for (j = 0; j < w; j++) {
            if (hfmcoding[j][1] == 0) {// 只在尚未构造二叉树的结点中查找(双亲为零的节点)
                if (hfmcoding[j][0] < min1) {
                    min2 = min1;
                    s[1] = s[0];
                    min1 = hfmcoding[j][0];
                    s[0] = j;

                } else if (hfmcoding[j][0] < min2) {
                    min2 = hfmcoding[j][0];
                    s[1] = j;
                }
            }
        }

        return s;
    }

    public String[] CreateHCode() {// 根据哈夫曼树求哈夫曼编码
        int n = charsAndWeight.length;
        int i, f, c;
        String hcodeString = "";
        hcs = new String[n];
        for (i = 0; i < n; i++) {// 根据哈夫曼树求哈夫曼编码
            c = i;
            hcodeString = "";
            f = hfmcoding[i][1]; // f 哈弗曼树的根节点
            while (f != 0) {// 循序直到树根结点
                if (hfmcoding[f][2] == c) {// 处理左孩子结点
                    hcodeString += "0";
                } else {
                    hcodeString += "1";
                }
                c = f;
                f = hfmcoding[f][1];
            }
            hcs[i] = new String(new StringBuffer(hcodeString).reverse());
        }
        return hcs;
    }

    public String show(String s) {// 对字符串显示编码
        String textString = "";
        char c[];
        int k = -1;
        c = new char[s.length()];
        c = s.toCharArray();// 将字符串转化为字符数组
        for (int i = 0; i < c.length; i++) {
            k = c[i];
            for (int j = 0; j < charsAndWeight.length; j++)
                if (k == charsAndWeight[j][0])
                    textString += hcs[j];
        }
        return textString;

    }

    // 哈弗曼编码反编译
    public String reCoding(String s) {

        String text = "";// 存放反编译后的字符
        int k = 0, m = hfmcoding.length - 1;// 从根节点开始查询
        char c[];
        c = new char[s.length()];
        c = s.toCharArray();
        k = m;
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '0') {
                k = hfmcoding[k][2];// k的值为根节点左孩子的序号
                if (hfmcoding[k][2] == 0 && hfmcoding[k][3] == 0)// 判断是不是叶子节点,条件(左右孩子都为零)
                {
                    text += (char) charsAndWeight[k][0];
                    k = m;
                }
            }
            if (c[i] == '1') {
                k = hfmcoding[k][3];// k的值为根节点右孩子的序号
                if (hfmcoding[k][2] == 0 && hfmcoding[k][3] == 0)// 判断是不是叶子节点,条件(左右孩子都为零)
                {
                    text += (char) charsAndWeight[k][0];
                    k = m;
                }

            }
        }
        return text;
    }
}


 

人民币转成大写

Java code
/**
     * 人民币转成大写
     *
     * @param value
     * @return String
     */
    public static String hangeToBig(double value)
    {
        char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
        char[] vunit = { '万', '亿' }; // 段名表示
        char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
        long midVal = (long) (value * 100); // 转化成整形
        String valStr = String.valueOf(midVal); // 转化成字符串

        String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
        String rail = valStr.substring(valStr.length() - 2); // 取小数部分

        String prefix = ""; // 整数部分转化的结果
        String suffix = ""; // 小数部分转化的结果
        // 处理小数点后面的数
        if (rail.equals("00"))
        { // 如果小数部分为0
            suffix = "整";
        }
        else
        {
            suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
        }
        // 处理小数点前面的数
        char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
        char zero = '0'; // 标志'0'表示出现过0
        byte zeroSerNum = 0; // 连续出现0的次数
        for (int i = 0; i < chDig.length; i++)
        { // 循环处理每个数字
            int idx = (chDig.length - i - 1) % 4; // 取段内位置
            int vidx = (chDig.length - i - 1) / 4; // 取段位置
            if (chDig[i] == '0')
            { // 如果当前字符是0
                zeroSerNum++; // 连续0次数递增
                if (zero == '0')
                { // 标志
                    zero = digit[0];
                }
                else if (idx == 0 && vidx > 0 && zeroSerNum < 4)
                {
                    prefix += vunit[vidx - 1];
                    zero = '0';
                }
                continue;
            }
            zeroSerNum = 0; // 连续0次数清零
            if (zero != '0')
            { // 如果标志不为0,则加上,例如万,亿什么的
                prefix += zero;
                zero = '0';
            }
            prefix += digit[chDig[i] - '0']; // 转化该数字表示
            if (idx > 0)
                prefix += hunit[idx - 1];
            if (idx == 0 && vidx > 0)
            {
                prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
            }
        }

        if (prefix.length() > 0)
            prefix += '圆'; // 如果整数部分存在,则有圆的字样
        return prefix + suffix; // 返回正确表示
    }


 

 

java 字符串解析

Java code
StringTokenizer tokenizer = new StringTokenizer(number, ",");
        boolean bool = true;
        while (tokenizer.hasMoreTokens()) {
            try {
                Double.valueOf(tokenizer.nextToken());
            } catch (Exception e) {
                bool = false;
            }
        }
//将字符串转化为数组的方法
int gv[];
   int i = 0;
   StringTokenizer tokenizer = new StringTokenizer(goodsVolume, ",, ");
         gv = new int[tokenizer.countTokens()];//动态的决定数组的长度
     while (tokenizer.hasMoreTokens()) {
        String d = tokenizer.nextToken();
        gv[i] = Integer.valueOf(d);//将字符串转换为整型
        i++;
    }

 //字符串解析
    private String[] stringAnalytical(String str, String divisionChar) {
        String string[];
       int i = 0;
        StringTokenizer tokenizer = new StringTokenizer(str, divisionChar);
        string = new String[tokenizer.countTokens()];// 动态的决定数组的长度
         while (tokenizer.hasMoreTokens()) {
            string[i] = new String();
            string[i] = tokenizer.nextToken();
            i++;
        }
        return string;// 返回字符串数组
    }

 int countTokens()
          计算在生成异常之前可以调用此 tokenizer 的 nextToken 方法的次数。
 boolean hasMoreElements()
          返回与 hasMoreTokens 方法相同的值。
 boolean hasMoreTokens()
          测试此 tokenizer 的字符串中是否还有更多的可用标记。
 Object nextElement()
          除了其声明返回值是 Object 而不是 String 之外,它返回与 nextToken 方法相同的值。
 String nextToken()
          返回此 string tokenizer 的下一个标记。
 String nextToken(String delim)
          返回此 string tokenizer 的字符串中的下一个标记。


public class StringAnalytical {

    // 字符串解析,将字符串转根据分割符换成字符串数组
    private String[] stringAnalytical(String string, char c) {
        int i = 0;
        int count = 0;

        if (string.indexOf(c) == -1)
            return new String[] { string };// 如果不含分割符则返回字符本身
        char[] cs = string.toCharArray();
        int length = cs.length;
        for (i = 1; i < length - 1; i++) {// 过滤掉第一个和最后一个是分隔符的情况
            if (cs[i] == c) {
                count++;// 得到分隔符的个数
            }
        }
        String[] strArray = new String[count + 1];
        int k = 0, j = 0;
        String str = string;
        if ((k = str.indexOf(c)) == 0)// 去掉第一个字符是分隔符的情况
            str = str.substring(k + 1);
        if (str.indexOf(c) == -1)// 检测是否含分隔符,如果不含则返回字符串
            return new String[] { str };
        while ((k = str.indexOf(c)) != -1) {// 字符串含分割符的时候
            strArray[j++] = str.substring(0, k);
            str = str.substring(k + 1);
            if ((k = str.indexOf(c)) == -1 && str.length() > 0)
                strArray[j++] = str.substring(0);
        }
        return strArray;
    }

    public void printString(String[] s) {
        System.out.println("*********************************");
        for (String str : s)
            System.out.println(str);
    }

    public static void main(String[] args) {
        String[] str = null;
        StringAnalytical string = new StringAnalytical();
        str = string.stringAnalytical("1aaa", '@');
        string.printString(str);
        str = string.stringAnalytical("2aaa@", '@');
        string.printString(str);
        str = string.stringAnalytical("@3aaa", '@');
        string.printString(str);
        str = string.stringAnalytical("4aaa@bbb", '@');
        string.printString(str);
        str = string.stringAnalytical("@5aaa@bbb", '@');
        string.printString(str);
        str = string.stringAnalytical("6aaa@bbb@", '@');
        string.printString(str);
        str = string.stringAnalytical("@7aaa@", '@');
        string.printString(str);
        str = string.stringAnalytical("@8aaa@bbb@", '@');
        string.printString(str);
        str = string.stringAnalytical("@9aaa@bbb@ccc", '@');
        string.printString(str);
        str = string.stringAnalytical("@10aaa@bbb@ccc@eee", '@');
        string.printString(str);
    }
}


 

java导出成Excel的方法(需要jxl.jar包)


Java code


import java.io.File;
import java.sql.ResultSet;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;

public class Export2Excel {

    public Export2Excel(Shell shell, String[] coloumNames, ResultSet rSet,
            String sheetName) {
        FileDialog fileDialog = new FileDialog(shell, SWT.NONE);
        fileDialog.setFilterExtensions(new String[]{"*.xls"});
        fileDialog.setText("文件另存为");
        fileDialog.setFileName("temp.xls");
        fileDialog.open();
        String path = fileDialog.getFilterPath();
        String fileName = fileDialog.getFileName();
        try {
            WritableWorkbook book = Workbook.createWorkbook((new File(path
                    + "\\" + fileName)));
            WritableSheet sheet = book.createSheet(sheetName, 0);
            for (int i = 0; i < coloumNames.length; i++) {
                sheet.setColumnView(100, 400);
                Label label = new Label(i, 0, coloumNames[i]);
                sheet.addCell(label);
            }
            int i = 0;
            while (rSet.next()) {
                i = i + 1;
                Label label1A = new Label(0, i, rSet.getRow() + "");
                sheet.addCell(label1A);
                for (int j = 0; j < coloumNames.length; j++) {
                    System.out.println("j =" + j);
                    if (j == 0) {
                        Label label = new Label(j, i, rSet.getRow() + "");
                        sheet.addCell(label);
                    } else {
                        Label label = new Label(j, i, rSet.getString(j));
                        sheet.addCell(label);
                    }
                }
            }
            book.write();
            book.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值