zoukankan      html  css  js  c++  java
  • java常用代码

    java常用代码

    一、字符串处理及常用类

    * 比较字符串,忽略大小写,直接用equalsIgnoreCase(),不要用toUpperCase()。

    String test="test";
    String test2="TEST";
    if(test.equalsIgnoreCase(test2)) {
        System.out.printf("trueCode");
    }

    * 字符串比较是否相等,使用StringUtils比较,不会报空指针异常:

    String str1="test";
    String str2="test";
    if (StringUtils.equals(str1,str2)){
    
    }

     * String字符串格式化,使用String.format():

    String name="lin";
    String result="111";
    System.out.println(String.format("%s输出结果为:%s",name,result));

    * 判断字符串是否为数字,使用apache-common包.

    String range="-0.3";
    if (NumberUtils.isNumber(range)) {
                System.out.println(true);
    }

     NumberUtils.isNumber()可以包含小数点。

    NumberUtils.isDigits()不可以包含小数点。。

    String num="123";
    boolean isNum=NumberUtils.isDigits(num);

    也可以使用StringUtils.isNumeric()。

    * 判断字符是否为字母,使用 Character.isLetter()。

    * 判断字符串是否全部为字母,可以使用StringUtils.isAlpha()。

     * 反转字符串:

    String str="abcd";
    String str2 = StringUtils.reverse(str);
    

     * 判断字符串中某个字符出现了几次,并将结果输出

    String str="abcabcda";
    int charCount=0;
    for(int i=0;i<str.length();i++) {
    //如果对应位置的字符为a,就计数.
    if(str.charAt(i)=='a') {   
      charCount++;
    }
    }

    更方便的作法是:

    直接使用apache-commons-lang中的StringUtils包。如下:

    int count=StringUtils.countMatches("abcabcda","a");

     * 字符串参数最后一次出现在当前字符串中的下标:

    String str = "abcdefgooabcd";
    int index=str.lastIndexOf( "o" );

    * 按指定分割符拆分字符串

    String str={"abc,def,ghi,jkl"};
    //按","拆分字符串
    String[] splitStr=str.split(","); System.out.println("按分隔符拆分后的字符串是:"); for(int i=0;i<splitStr.length;i++){ System.out.print(newString[i]);
    }

    注意:split参数可以是普通字符,也可以是正则表达式。

    如果拆分的是特殊字符,要写转义字符。比如 ,按"."拆分 , 应该写 date.split("\.")[0]

    * 将数字型字符转化为数字。直接使用Character的api:

    char c='1';
    int num=Character.getNumericValue(c)
    ;

    * 遍历字符串。

    示例,判断字符串中,某些范围内的字符,比如从n到z,出现的次数。

     想要遍历字符串并比较字符,最好将字符串转化为字符数组.

     将字符串转换为字符数组,只需要用toCharArray()方法。

    public int printCharNumbers(String s) {
        int cNumber=0;
        for(char c: s.toCharArray()) {
            if(c>'m' && c<='z')
                cNumber++;
        }
        return cNumber;
    }

     * 字符串通过间隔符拼接:

    StringJoiner sj = new StringJoiner("-");
    sj.add("123").add("abc");
    String result = sj.toString();
    System.out.print(result);    //结果为 "123-abc"

    二、日期时间

    * SimpleDateFormat:

    注意:表达年份时,要使用yyyy,如果使用了YYYY,会导致年份出错。

    * Date转String:

    public void stringToDate(Date date){    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str=sdf.format(date);
    }

    * String转Date:

    public void stringToDate() throws ParseException{    
        String str="2016-07-21 15:41:52";
        Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
    }

     * 用Calendar设置时间。获取Calendar对应的时间。

    public void getCalendarTime(Date date) {
            Calendar calendar = Calendar.getInstance();
            //通过calendar设置时间
            calendar.setTime(date);
            //获取calendar对应的时间
            Date time = calendar.getTime();
            System.out.println(time);
    }

    * 用Calendar设置年月日。获取年月日。

        public static void setCalendarMonthDay() {
            Calendar calendar = Calendar.getInstance();
            //通过Calendar设置年月日
            calendar.set(Calendar.MONTH, 7);
            calendar.set(Calendar.DAY_OF_MONTH, 7);
            calendar.set(Calendar.YEAR, 2018);
            calendar.set(Calendar.HOUR_OF_DAY,19);
            //通过Calendar获取时间,年月日
            Date date = calendar.getTime();
            int year = calendar.get(Calendar.YEAR);
            //Calendar的月份是从0开始计算的,所以要加一才是真实的月份
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            System.out.println(date);
            System.out.println("year:" + year);
            System.out.println("month:" + month);
            System.out.println("day:" + day);
            System.out.println("hour:" + hour);
        }

    * 比较日期大小:

        public static void compareDate(Date date1,Date date2) {
            if (date1.compareTo(date2) == 0) {
                System.out.println(date1+"等于"+date2);
            }
        }

    * 获取当前系统时间:

    long currentTime = System.currentTimeMillis(); //获取系统时间
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒");
    Date date = new Date(currentTime);
    System.out.println(formatter.format(date));

     

    二、正则表达式示例

    正则表达式的规则见: https://www.cnblogs.com/expiator/p/12250598.html

    1.用正则表达式验证字符串格式。

    String str="QQabc4755";
    boolean b1=str.matches("\p{Upper}{2}\p{Lower}{3}\d{4}");        //用正则表达式判断字符串格式
    if(b1) {
      System.out.println("该字符串是合法数据");
    }else {       
      System.out.println("该字符串不是合法数据");
    }

     

    2.用正则表达式检查日期字符串是否符合格式

    public class MatchesDemo {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
    //          String dateStr="2016-06-18 01:09:32";
    //          String dateStr="2016-6-18 02:09:32";
              String dateStr="2016-6-8 03:09:32";
              String regex1="\d{4}-\d{1}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}";
              String regex2="\d{4}-\d{2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}";
              String date=null;
            if(dateStr.matches(regex1)){ //regex1验证的是"2016-6-18 02:09:32"
                  System.out.println(dateStr+"是日期字符串");
                  String[] splitStr=dateStr.split("-");
                  date=splitStr[0]+"0"+splitStr[1];
                  System.out.println("提取得到的日期是:"+date);
              }
            if(dateStr.matches(regex2)){ //regex2验证的是"2016-06-18 01:09:32"
                System.out.println(dateStr+"是日期字符串");
                String[] splitStr=dateStr.split("-");
              date=splitStr[0]+splitStr[1];
              System.out.println("提取得到的日期是:"+date);
            }  

        }

    }

     

    3.用正则表达式检查日期字符串是否符合格式

    String str="1983-07-27";    //检查日期格式是否正确
    String regex="\d{4}-\d{2}-\d{2}";
    Pattern p=Pattern.compile(regex);   //先声明模式
    Matcher m=p.matcher(str);    //接着再匹配
    if(m.matches())  {
            System.out.println("日期格式合法");    
    }else {
        System.out.println("日期格式不合法");
    }

     

    4.统计文本中各个单词出现的次数.

    public static  Map<String ,Integer> countEachWord(String str){
      //正则表达式[A-Za-z]+表示一个以上的任意字母的字符 Matcher m
    = Pattern.compile("[A-Za-z]+").matcher(str); String matcheStr=null; Map<String ,Integer> map=new LinkedHashMap<>(); Integer count=0;
    //m.find()查看是否存在匹配的子字符串,m.group()返回匹配的子字符串
    while(m.find()){ matcheStr=m.group().toLowerCase(); count=map.get(matcheStr); map.put(matcheStr, count!=null?count+1:1); } return map; }

     

    5.替换字符串。

    使用正则表达式,想要匹配+[.?^{|,需要在前面加上一个转义字符,也就是

    String test="A.B.C.D";
    String test2=test.replaceAll("\.","[.]");

    6.正则表达式,匹配,查找,分组:

    public static void patternDemo() {
            String formula="100.00/10.00-200.00/(30.0-10.00)";
            // 匹配格式:100/10 或者 100.00/10.00 或者 200.00/(30.0-10.00)
            Pattern pattern = Pattern.compile("(\d+/\(\d+.*\))|(\d+\.?\d+/\d+\.?\d+)");
            Matcher matcher = pattern.matcher(formula.replaceAll(" ",""));
            while (matcher.find()) {
                String group = matcher.group();
                System.out.println("group:" + group);
            }
        }

    三、多线程

    1.继承thread,实现多线程.

    public class ThreadDemo {
      public static void main(String args[]){
          Mythread thread1=new Mythread("thread1");
          Mythread thread2=new Mythread("thread2");
          thread1.start();        //开始线程,启动run方法
               thread2.start();      //运行结果中,两个线程是交错运行的,哪个线程抢到CPU资源,哪个对象线程就会运行
      }                               //每次的运行结果都不一样
    }
    
    class Mythread extends Thread{         //继承Thread实现多线程
        private String name;
        public Mythread(String name){
            this.name=name;
        }
        public void run(){
            for(int i=0;i<10;i++)
               System.out.println(name+"运行次数:"+i);
        }
    
    }

     


    2.实现Runnable接口,实现多线程

    public class RunnableDemo {
      public static void main(String args[]){
          MyThread thread1=new MyThread("线程A");
          MyThread thread2=new MyThread("线程B");
          Thread t1=new Thread(thread1);         //将实现了runnable接口的对象作为参数
               Thread t2=new Thread(thread2);
              t1.start();
          t2.start();
      }
    }
    class MyThread implements Runnable{ //实现Runnable接口 private String name; public MyThread(String name){ this.name=name; } public void run(){ //定义run()方法 for(int i=0;i<10;i++){ System.out.println(name+"运行次数"+i); } } }

     


    3.使用线程同步解决问题,可以使用同步代码块和同步方法两种来完成。同步方法的关键字synchronized

    class Ticket implements Runnable {
        public void run() {
            for (int i = 0; i < 10; ++i) {
                sale();
            }
        }
     
        public synchronized void sale() {       //在方法名前面添加互斥锁,保证同步
            if (count > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(count--);
            }
        }
     
        public static void main(String[] args) {
            Ticket he = new Ticket();
            Thread h1 = new Thread(he);   //将runnable对象做为参数,新建线程
            Thread h2 = new Thread(he);
            Thread h3 = new Thread(he);
            h1.start();
            h2.start();
            h3.start();
        }
     
        private int count = 5;
    }

     

    四、文件操作

    1.读取文件的每一行数据

    public void ReadFileByLines(String fileName)  throws Exception{
        File file=new File(fileName);
        BufferedReader reader=new BufferedReader(new FileReader(file));
        String lineString;
        int line=1;
        while((lineString=reader.readLine())!=null){    //读取每一行
        if(lineString.isEmpty())   continue;       //如果是空格,就跳过
        System.out.println("line"+line+" :"+lineString);
        line++;    
     }
        reader.close();
    }

     
    2.检验文件是否存在。

       File file=new File("D:\mywork\work.txt");
         if(file.exists()) {      //
              file.delete();  System.out.println("文件已删除");
          } else {
                try{
                   file.createNewFile(); System.out.println("文件已创建");
                } catch(Exception e) { e.printStackTrace() }
          
          }

     


    3.从键盘输入内容到文件中,然后从文件中读取数据;
     

          File file=new File("F:/IO操作","fileStream.txt");   //创建文件对象
            try {
                FileOutputStream out=new FileOutputStream(file);  //创建输出流对象
                System.out.println("请输入内容:");
                Scanner sc=new Scanner(System.in);           //从键盘获取数据
                byte byte1[]=sc.nextLine().getBytes();   //获取字节."IO操作的文件流和字节流"
                out.write(byte1);       //将字节数组写入到文件输出流中。  
                out.close();                //记得将流关闭。
                
                FileInputStream in=new FileInputStream(file);   //创建输入流对象
                byte[] byte2=new byte[1024];
                int len =in.read(byte2);    //获取文件长度.
                System.out.println("目标文件中的内容是:"+new String(byte2,0,len));   //将字节数组转化为字符串
             }catch(Exception e){
                  e.printStackTrace();
             }     

     
            
    4.使用字符流,将字符串写入文件

    public class WriteDemo {
        public static void main(String[] args) {
               File file=new File("F:\IO操作","work.txt");
              try{
               Writer out=new FileWriter(file);
               String str="hello world";
               out.write(str);          //字符流可以直接写入字符串,而不用字节数组
               out.close();        //字符流存在缓冲区,必须关闭流。
              }catch(IOException e){
                  e.printStackTrace();
                  
              }
        }
    } 

     
    五、集合


    1.用迭代器iterator遍历集合

    
    
        /**
         * 遍历List
         */
        public  void Ergodic(List<String> list){
              for(String str : list) {
                  System.out.println(str);
              }
        }

        /**
         * 通过Iterator遍历
         */
        public void ErgodicByIterator(List<String> list){
            //创建集合的迭代器
            Iterator<String> iterator=list.iterator();
            //hasNext()检验是否还有下一个.
            //用迭代器遍历list
            while(iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }
     

     



    2.ArrayList可通过get()方法获取对应索引的字符串
    示例代码:

    List<String> list=new ArrayList<String>();
    list.add("abc");  list.add("def");
    System.out.println(list.get(0));  //输出abc
    System.out.println(list.get(1));

     



    3.Map集合中的元素是通过key,value(键值对)存储的。
    向Map中添加元素,必须用put();

    Map<String,String> map=new HashMap<String,String>();
    map.put("key", "value");        //添加键值对
    map.remove("key"); 

     

    4.入栈、出栈操作

    push入栈,pop出栈,peek查看但不移除.top查看栈顶

    public class StackDemo {
        public static void main(String[] args) {
            Stack<String> stack=new Stack<String>();
            stack.push("a");
            stack.push("b");
            stack.push("c");
            while(!stack.isEmpty()) {
                System.out.println(stack.pop());
            }
        }
    }

     


    六、数据库编程
    1.验证驱动是否成功加载

    public class ConnectionDemo {
        //定义MySQL的数据库驱动程序
        public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
        public static void main(String args[]){
            try{
                Class.forName(DBDRIVER) ;
                System.out.println("mysql驱动成功加载.");
            }catch(ClassNotFoundException e){
                System.out.println("mysql驱动加载失败");
                e.printStackTrace() ;
            }}
    }

     


    2.查询数据库

    public class ResultSetDemo {
        public static final String DBDRIVER="org.gjt.mm.mysql.Driver";
        public static final String DBURL="jdbc:mysql://localhost:3306/workers";        //最后的“workers”为数据库名称
        public static final String  DBUSER="root";     //用户名
        public static final String DBPASS="root";       //密码
       public static void main(String argst[]) throws Exception{
          Connection conn;  //数据库连接
          Statement stmt;   //数据库操作
          String sql="select id,name,sex from coders ";
          Class.forName(DBDRIVER);  //加载驱动
          conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS); //连接数据库
          stmt=conn.createStatement();   //实例化Statement对象
          ResultSet rs=stmt.executeQuery(sql);      //执行数据库查询操作
          while(rs.next()){        //指针移动下一行
            int id=rs.getInt(1);             //获取数据
            String name=rs.getString(2);
            String sex=rs.getString(3);
            System.out.print("编号:"+id+";");
            System.out.print("姓名:"+name+";");
            System.out.println("性别:"+sex+"");
          }
          
          rs.close();                     //关闭结果集
          stmt.close();                //操作关闭
          conn.close();                 //数据库关闭
       }
    }

     



    3.将数据插入数据库。或者更新、删除。

    public class InsertIntoDemo {
        public static final String DBDRIVER="org.gjt.mm.mysql.Driver";
        public static final String URL="jdbc:mysql://localhost:3306/workers";
        public static final String USER="root";
        public static final String PASSWORD="root";
        
        public static void main(String[] args) throws Exception{
            // TODO Auto-generated method stub
            
            Class.forName(DBDRIVER);
            Connection conn=DriverManager.getConnection(URL,USER,PASSWORD);
            Statement stmt=conn.createStatement();
            String sql="insert into coders values (3,'chenbin',27,'female')";
            stmt.executeUpdate(sql);     //执行更新操作
    conn.commit(); //提交事务 stmt.close(); conn.close(); } }

     

    4.预处理操作PrepareStatement

     

        public static final String DBDRIVER="org.gjt.mm.mysql.Driver";
        public static final String URL="jdbc:mysql://localhost:3306/workers";
        public static final String USER="root";
        public static final String PASSWORD="root";

    public List<Message> findAllMessagee(Page page) { Class.forName(DBDRIVER);
      Connection conn=DriverManager.getConnection(URL,USER,PASSWORD);
    String findSQL = "select * from tb_message " + "order by publishTime desc limit ?,?"; PreparedStatement pstmt = null; //声明预处理对象 ResultSet rs = null; List<Message> messages = new ArrayList<Message>(); try { pstmt = conn.prepareStatement(findSQL); //获得预处理对象并赋值 pstmt.setInt(1, page.getBeginIndex()); //查询起始点 pstmt.setInt(2, page.getEveryPage()); //查询记录数 rs = pstmt.executeQuery(); //执行查询 while(rs.next()) { Message message = new Message(); message.setMessageID(rs.getInt(1)); //设置消息ID message.setMessageTitle(rs.getString(2));//设置消息标题 message.setMessageContent( rs.getString(3)); //设置消息内容 message.setEmployeeID(rs.getInt(4));//设置员工编号 message.setPublishTime(rs.getTimestamp(5));//设置发布时间 messages.add(message);//添加消息 } } catch (SQLException e) { e.printStackTrace(); } finally{  rs.close();                     //关闭结果集
      stmt.close();                //操作关闭
      conn.close();                 //数据库关闭
    } return messages; }

     七、反射

    1.获取类名,方法名

     String clazz = Thread.currentThread() .getStackTrace()[1].getClassName();
     String method = Thread.currentThread() .getStackTrace()[1].getMethodName();
     System.out.println("class:"+clazz+"
    method:"+method);

    2.其他的反射代码块:

    https://www.cnblogs.com/expiator/p/8340948.html

  • 相关阅读:
    模拟赛总结
    2018.04.06学习总结
    2018.04.06学习总结
    Java实现 LeetCode 672 灯泡开关 Ⅱ(数学思路问题)
    Java实现 LeetCode 671 二叉树中第二小的节点(遍历树)
    Java实现 LeetCode 671 二叉树中第二小的节点(遍历树)
    Java实现 LeetCode 671 二叉树中第二小的节点(遍历树)
    Java实现 LeetCode 670 最大交换(暴力)
    Java实现 LeetCode 670 最大交换(暴力)
    Java实现 LeetCode 670 最大交换(暴力)
  • 原文地址:https://www.cnblogs.com/expiator/p/5544247.html
Copyright © 2011-2022 走看看