• 常用java代码1(转)


    JAVA访问XML文件

    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文件如下:
    
    <?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日期处理Bean

    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();
        }
    
        
       
       
  • 相关阅读:
    汇编指令(它不区分大小写)
    汇编
    LINUX命令
    LInux 终端命令
    回文串的Manacher算法
    hdu3336 Counting the string kmp的next数组的应用
    hdu2203kmp匹配
    hdu2087kmp模板练习
    hdu1171kmp果题
    hdu1686kmp果题
  • 原文地址:https://www.cnblogs.com/CodeMaker/p/Userful.html
Copyright © 2020-2023  润新知