Java API学习笔记

一、字符串类

1.1 String类的初始化,几个常见的构造方法

String() //创建一个内容为空的字符串
String(String value) //根据指定的字符串内容创建对象
String(char[] value) //根据指定的字符数组创建对象
String(byte[] bytes) //根据指定的字节数组创建对象

  String测试案例

public class test8 {
    public static void main(String[] args)throws Exception{
        //创建一个空的字符串
        String str1=new String();
        //创建一个内容为abcd的字符串
        String str2=new String("abcd");
        //创建一个内容为字符数组的字符串
        char[] charArray=new char[] {'D','E','F'};
        String str3=new String(charArray);
        //创建一个内容为字节数组的字符串
        byte[] arr={97,98,99};
        String str4=new String(arr);
        //打印
        System.out.println("a"+str1+"b");
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
    }
}

输出结果

ab
abcd
DEF
abc

1.2 String类的常见操作

//返回指定字符ch在字符串中第一次出现的位置的索引
int indexOf(int ch)

//返回指定字符ch在字符串中最后一次出现的位置的索引
int lastIndexOf(int ch)

//返回指定字符串str在字符串第一次出现位置的索引
int indexOf(String str)

//返回指定字符串str在此字符串中的最后一次出现位置的索引
int lastIndexOf(String str)

1.2.1 字符串的获取功能

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        String s="ababcdedcda";
        System.out.println("字符串的长度为:"+s.length());
        System.out.println("字符串中第一个字符:"+s.charAt(0));
        System.out.println("字符c第一次出现的位置:"+s.indexOf('c'));
        System.out.println("字符c最后一次出现的位置:"+s.lastIndexOf('c'));
        System.out.println("子字符串ab第一次出现的位置:"+s.indexOf("ab"));
        System.out.println("子字符串ab最后一次出现的位置:"+s.lastIndexOf("ab"));
    }
}

 【运行代码】

字符串的长度为:11
字符串中第一个字符:a
字符c第一次出现的位置:4
字符c最后一次出现的位置:8
子字符串ab第一次出现的位置:0
子字符串ab最后一次出现的位置:2

1.2.2 字符串的转换操作

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        String str="ababcdedcda";
        System.out.print("将字符串转换为字符数组后的结果:");
        char[] charArray=str.toCharArray(); //字符串转化为字符数组
        for(int i=0;i<charArray.length;i++){
            if (i !=charArray.length-1){
                //如果不是数组的最后一个元素,在元素后面加逗号
                System.out.print(charArray[i]+",");
            }else{
                //数组的最后一个元素后面不加逗号
                System.out.println(charArray[i]);
            }
        }
        System.out.println("将int值转换为String类型之后的结果:"+String.valueOf(12));
        System.out.println("将字符串转换为大写字母之后的结果:"+str.toUpperCase());
        System.out.println("将字符串转换为小写字母之后的结果:"+str.toLowerCase());

    }
}

【运行结果】

将字符串转换为字符数组后的结果:a,b,a,b,c,d,e,d,c,d,a
将int值转换为String类型之后的结果:12
将字符串转换为大写字母之后的结果:ABABCDEDCDA
将字符串转换为小写字母之后的结果:ababcdedcda

1.2.3 字符串的替换和去除空格操作

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        String s="itcast";
        //字符串替换操作
        System.out.println("将it替换成cn.it的结果:"+s.replace("it", "cn.it"));
        //字符串去除空格操作
        String s1="    i t c a s t       ";
        System.out.println("去除字符串两端空格后的结果:"+s1.trim());
        System.out.println("去除字符串所有空格后的结果:"+s1.replace(" ", ""));

    }
}

【运行结果】

将it替换成cn.it的结果:cn.itcast
去除字符串两端空格后的结果:i t c a s t
去除字符串所有空格后的结果:itcast

1.2.4 字符串的判断操作

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        String s1="String";
        String s2="Str";
        System.out.println("判断是否以字符串Str开头:"+s1.startsWith("Str"));
        System.out.println("判断是否以字符串ng结尾:"+s1.endsWith("ng"));
        System.out.println("判断是否包含字符串tri:"+s1.contains("tri"));
        System.out.println("判断字符串是否为空:"+s1.isEmpty());
        System.out.println("判断两个字符串是否相等:"+s1.equals(s2));

    }
}

【运行结果】

判断是否以字符串Str开头:true
判断是否以字符串ng结尾:true
判断是否包含字符串tri:true
判断字符串是否为空:false
判断两个字符串是否相等:false

1.2.5 字符串的截取和分割

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        String str = "石家庄-武汉-哈尔滨";
        //截取操作
        System.out.println("从第5个字符截取到末尾的结果:"+str.substring(4));
        System.out.println("从第5个字符截取到第6个字符的结果:"+str.substring(4,6));
        //字符串分割操作
        System.out.println("分割后的字符串数组中的元素依次为:");
        String[] strArray=str.split("-"); //将字符串转换为字符串数组
        for(int i=0;i<strArray.length;i++){
            //如果不是数组的最后一个元素,在元素后面加,
            if(i!=strArray.length-1){
                System.out.print(strArray[i]+",");
            }else{
                System.out.print(strArray[i]);
            }
        }
    }
}

【运行结果】

从第5个字符截取到末尾的结果:武汉-哈尔滨
从第5个字符截取到第6个字符的结果:武汉
分割后的字符串数组中的元素依次为:
石家庄,武汉,哈尔滨

1.3 StringBuffer类

1.3.1 StringBuffer类常用方法

 【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        System.out.println("1、添加------------------");
        add();
        System.out.println("2、删除------------------");
        remove();
        System.out.println("3、修改------------------");
        alter();
    }
    public static void add(){
        StringBuffer sb=new StringBuffer(); //创建一个字符串的缓存区
        sb.append("itcast"); //在末尾添加字符串
        System.out.println("append添加结果:"+sb);
        sb.insert(2, "123"); //在指定位置插入字符串
        System.out.println("insert添加结果:"+sb);
    }
    public static void remove(){
        StringBuffer sb = new StringBuffer("itcastcn");
        sb.delete(1, 5); //指定位置删除
        System.out.println("删除指定位置结果:"+sb);
        sb.deleteCharAt(2);
        System.out.println("删除指定位置结果:"+sb);
        sb.delete(0, sb.length()); //清空缓存区
        System.out.println("清空缓存区结果:"+sb);
    }
    public static void alter(){
        StringBuffer sb = new StringBuffer("itcastcn");
        sb.setCharAt(1, 'p'); //修改指定位置字符
        System.out.println("修改指定位置字符结果:"+sb);
        sb.replace(1, 3, "qq");
        System.out.println("替换指定位置字符(串)结果:"+sb);
        System.out.println("字符串反转结果:"+sb.reverse());
    }
}

【运行结果】

1、添加------------------
append添加结果:itcast
insert添加结果:it123cast
2、删除------------------
删除指定位置结果:itcn
删除指定位置结果:itn
清空缓存区结果:
3、修改------------------
修改指定位置字符结果:ipcastcn
替换指定位置字符(串)结果:iqqastcn
字符串反转结果:nctsaqqi

1.4 string Builder类

【案例】

public class test8 {
    private static final int TIMES=100000;
    public static void main(String[] args)throws Exception{
        test8.testString();
        test8.testStringBuffer();
        test8.testStringBuilder();
    }
    //String时间效率测试
    public static void testString(){
        long startTime=System.currentTimeMillis();
        String str = "";
        for(int i=0;i<TIMES;i++){
            str +="test";
        }
        long endTime=System.currentTimeMillis();
        System.out.println("String test usedtime:"+(endTime-startTime));
    }
    //StringBuffer时间效率测试(线程安全)
    public static void testStringBuffer(){
        long startTime=System.currentTimeMillis();
        StringBuffer str=new StringBuffer();
        for(int i=0;i<TIMES;i++){
            str.append("test");
        }
        long endTime=System.currentTimeMillis();
        System.out.println("StringBuffer test usedtime:"+(endTime-startTime));
    }
    //StringBuilder时间效率测试(非线程安全)
    public static void testStringBuilder(){
        long startTime=System.currentTimeMillis();
        StringBuilder str=new StringBuilder();
        for(int i=0;i<TIMES;i++){
            str.append("test");
        }
        long endTime=System.currentTimeMillis();
        System.out.println("StringBuilder test usedtime:"+(endTime-startTime));
    }

}

【运行结果】

可以观察到三者的工作效率是StringBuilder>StringBuffer>String

 二、System类与Runtime类

2.1 System类

System类的常用方法

 2.1.1 arraycopy()方法

arraycopy()方法用于将数组从源数组复制到目标数组。

声明格式如下:

static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
src:表示源数组
dest:表示目标数组
srcPos:表示源数组中复制元素的起始位置。
destPos:表示复制到目标数组的起始位置。
length:表示复制元素的个数。

 【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        int[] fromArray={10,11,12,13,14,15};//源数组
        int[] toArray={20,21,22,23,24,25,26};//目标数组
        System.arraycopy(fromArray, 2, toArray, 3, 4);//复制数组元素
        //打印复制后数组的元素
        System.out.println("复制后的数组元素:");
        for(int i=0;i<toArray.length;i++){
            System.out.println(i+":"+toArray[i]);
        }
    }

}

【运行结果】

0:20
1:21
2:22
3:12
4:13
5:14
6:15

2.1.2 currentTimeMillis()方法

currentTimeMillis()方法是用于获取当前系统的时间,返回的是long类型的值。

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        long startTime=System.currentTimeMillis();//循环开始时的当前时间
        int sum=0;
        for(int i=0;i<10000000;i++){
            sum+=i;
        }
        long endTime=System.currentTimeMillis();
        System.out.println("程序运行的时间为:"+(endTime-startTime)+"毫秒");
        }
    }

【运行结果】

程序运行的时间为:7毫秒

2.1.3 getProperties()和getProperty()方法

System类的getProperties()方法用于获取当前系统的全部属性。

该方法会返回一个Properties对象,其中封装了系统的所有属性。

getProperty()方法用于根据系统的属性名获取对应的属性值。

【案例】

import java.util.Enumeration;
import java.util.Properties;

public class test8 {
    public static void main(String[] args)throws Exception{
        //获取当前系统属性
        Properties properties=System.getProperties();
        //获得所有系统属性的key,返回Enumeration对象
        Enumeration propertyNames=properties.propertyNames();
        while (propertyNames.hasMoreElements()){
            //获取系统属性的key
            String key=(String)propertyNames.nextElement();
            //获得当前key对应的value
            String value=System.getProperty(key);
            System.out.println(key+"--->"+value);
        }
        }
    }

【运行结果】

java.runtime.name--->Java(TM) SE Runtime Environment
sun.boot.library.path--->E:\Java base\jdk\jre\bin
java.vm.version--->25.291-b10    // 虚拟机版本
java.vm.vendor--->Oracle Corporation
java.vendor.url--->http://java.oracle.com/
path.separator--->;
java.vm.name--->Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg--->sun.io
user.script--->
user.country--->CN           //用户所在国家
sun.java.launcher--->SUN_STANDARD
sun.os.patch.level--->Service Pack 1
java.vm.specification.name--->Java Virtual Machine Specification
user.dir--->E:\Java base\阶段复习二
java.runtime.version--->1.8.0_291-b10
java.awt.graphicsenv--->sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs--->E:\Java base\jdk\jre\lib\endorsed
os.arch--->amd64           //操作系统框架
java.io.tmpdir--->C:\Users\ADMINI~1\AppData\Local\Temp\
line.separator--->

java.vm.specification.vendor--->Oracle Corporation
user.variant--->
os.name--->Windows 7    //操作系统版本
sun.jnu.encoding--->GBK
java.library.path--->E:\Java 

2.1.4 gc()方法

垃圾回收机制

【案例】

import java.util.Enumeration;
import java.util.Properties;

class Person{
    //下面定义的finalize方法会在垃圾回收前被调用
    public void finalize(){
        System.out.println("对象将被作为垃圾回收...");
    }
}
public class test8 {
    public static void main(String[] args)throws Exception{
        //下面创建了两个Person对象
        Person p1=new Person();
        Person p2=new Person();
        //下面将变量置为null,让对象变为垃圾
        p1=null;
        p2=null;
        //调用方法进行垃圾回收
        System.gc();
        for(int i=0;i<100000;i++){
            //延长程序时间
        }
        
        }
    }

【运行代码】

对象将被作为垃圾回收...
对象将被作为垃圾回收...

在第3~5行代码定义了一个finalize()方法,该方法的返回值必须是void;第10~11行代码创建了两个对象p1和p2,然后将两个对象设置为null,这意味着新创建的两个对象成为垃圾;第16行代码通过"System.gc()"语句进行垃圾回收。

2.2 Runtime类

Runtime类用于表示虚拟机运行时的状态,它用于封装Java虚拟机进程。

Runtime类的常用方法

getRuntime() //该方法用于返回当前应用程序的运行环境对象
exec(String command) //该方法用于根据指定的路径执行对应的可执行文件
freeMemory() //该方法用于返回Java虚拟机中的空闲内存量,以字节为单位
maxMemory() //该方法用于返回Java虚拟机的最大可用内存量
availableProcessors() //该方法用于返回当前虚拟机的处理器个数
totalMemory() //该方法用于返回Java虚拟机中的内存总量

2.2.1 获取当前虚拟机的信息

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        Runtime rt=Runtime.getRuntime(); //获取
        System.out.println("处理器个数:"+rt.availableProcessors()+"个");
        System.out.println("空闲内存数量:"+rt.freeMemory()/1024/1024+"M");
        System.out.println("最大可用内存数量:"+rt.maxMemory()/1024/1024+"M");
        System.out.println("虚拟机中内存总量:"+rt.totalMemory()/1024/1024+"M");
        
        }
    }

【运行结果】

处理器个数:4个
空闲内存数量:59M
最大可用内存数量:885M
虚拟机中内存总量:61M

2.2.2 操作系统进程

Runtime类中提供了一个exec()方法,该方法用于执行一个DOS命令,从而实现与在命令行窗口中输入“dos”命令同样的效果

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        Runtime rt = Runtime.getRuntime(); //创建Runtime实例对象
        rt.exec("notepad.exe"); //调用exec()方法
        }
    }

【运行结果】

 同样Runtime类的exec()方法返回一个Process对象,该对象就是exec()所生成的新进程,通过该对象可以对产生的新进程进行管理,如关闭此进程只需调用destroy()方法即可

【运行代码】

public class test8 {
    public static void main(String[] args)throws Exception{
        Runtime rt = Runtime.getRuntime(); //创建Runtime实例对象
        Process process= rt.exec("notepad.exe");
        Thread.sleep(3000); //程序休眠3秒
        process.destroy();
        
        //调用exec()方法
        }
    }

【运行结果】 

程序被直接关闭

三、Math类与Random类

3.1 Math类

Math类的常用方法

abs() //该方法用于计算绝对值
sqrt() //该方法用于计算方根
ceil(a.b) //该方法用于计算大于参数的最小整数
floor() //该方法用于计算小于参数的最小整数
round() //该方法用于计算小数进行四舍五入后的结果
max() //该方法用于计算两个数的最大值
min() //该方法用于计算两个数的最小值
random() //该方法用于生成一个大于0.0小于1.0的随机数
pow() //该方法用于计算指数函数的值

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        System.out.println("计算绝对值的结果:"+Math.abs(-10));
        System.out.println("求大于参数的最小整数:"+Math.ceil(5.6));
        System.out.println("求小于参数的最大整数:"+Math.floor(-4.2));
        System.out.println("对小数进行四舍五入后的结果:"+Math.round(-4.6));
        System.out.println("求两个数的较大值:"+Math.max(2.1, -2.1));
        System.out.println("求两个数的较小值:"+Math.min(2.1, -2.1));
        System.out.println("生成一个大于等于0.0小于1.0的随机整数:"+Math.random());
        System.out.println("开平方的结果:"+Math.sqrt(4));
        System.out.println("指数函数的值:"+Math.pow(2, 3));
        }
    }

【运行结果】

计算绝对值的结果:10
求大于参数的最小整数:6.0
求小于参数的最大整数:-5.0
对小数进行四舍五入后的结果:-5
求两个数的较大值:2.1
求两个数的较小值:-2.1
生成一个大于等于0.0小于1.0的随机整数:0.5976859148771723
开平方的结果:2.0
指数函数的值:8.0

3.2 Random类

Java的java.util包中有一个Random类,它可以在指定的取值范围内随机产生数字。有两种构造方法,如下:

Random() //构造方法,用于创建一个伪随机数生成器
Random(long seed) //构造方法,使用一个long型的seed(种子)创建伪随机数生成器

第一种构造方法是无参的,通过它创建的Random实例对象每次使用的种子是随机的

第二种构造方法创建的多个Random实例对象产生的随机数是相同的

【案例】

第一种

import java.util.Random;

public class test8 {
    public static void main(String[] args)throws Exception{
        Random r = new Random(); //不传入种子
        //随机产生10个[0,100)之间的整数
        for(int x=0;x<10;x++){
            System.out.println(r.nextInt(100));
        }
        }
    }

【运行结果】

//运行第一次
76 63 27 63 50 22 14 57 9 73
//运行第二次
5 43 86 11 93 50 45 66 52 10

观察到两次结果不相同

第二种 有参

import java.util.Random;

public class test8 {
    public static void main(String[] args)throws Exception{
        Random r = new Random(13); //传入种子
        //随机产生10个[0,100)之间的整数
        for(int x=0;x<10;x++){
            System.out.println(r.nextInt(100));
        }
        }
    }

【运行结果】

当运行两次,如果种子相同,则输出的随机数也相同

85 88 47 13 54 4 34 6 78 48

85 88 47 13 54 4 34 6 78 48

Random类的常用方法

double nextDouble() //生成double类型的随机数
float nextFloat() //生成float类型的随机数
int nextInt() //生成int类型的随机数
int nextInt(int n) //生成0~n int类型的随机数

【案例】

import java.util.Random;

public class test8 {
    public static void main(String[] args)throws Exception{
        Random r = new Random();//创建Random实例对象
        System.out.println("产生float类型随机数:"+r.nextFloat());
        System.out.println("产生double类型随机数:"+r.nextDouble());
        System.out.println("产生int类型的随机数:"+r.nextInt());
        System.out.println("产生0~100之间int类型的随机数:"+r.nextInt(100));
        }
    }

【运行结果】

产生float类型随机数:0.7874738
产生double类型随机数:0.8759072710329671
产生int类型的随机数:-602545047
产生0~100之间int类型的随机数:83

4.日期时间类

表示日期时间的主要类

Instant  表示时刻,代表的是时间戳
LocalDate  不包含具体时间的日期
LocalTime  不包含日期的时间
LocalDateTime  包含了日期和时间
Duration  基于时间的值测量时间量
Period  计算日期时间差异,只能精确到年月日
Clock  时钟系统,用于查找当前日期

4.1 Instant类

Instant类代表的是某个时间

Instant类的常用方法

 【案例】

import java.time.Instant;

public class test8 {
    public static void main(String[] args)throws Exception{
        //Instant时间戳类从1970-01-01 00:00:00 截止到当前时间的毫秒值
        Instant now=Instant.now();
        System.out.println("从系统获取的当前时刻为:"+now);

        Instant instant = Instant.ofEpochMilli(1000*60*60*24);
        System.out.println("计算机元年增加毫秒数后为:"+instant);

        Instant instant1 = Instant.ofEpochSecond(60*60*24);
        System.out.println("计算机元年增加秒数后为:"+instant1);
        System.out.println("获取的秒值为:"+Instant.parse("2007-12-03T10:15:30.44z").getNano());
        System.out.println("从时间对象获取的Instant实例为:"+Instant.from(now));
        }
    }

【运行结果】

从系统获取的当前时刻为:2022-04-13T08:40:44.438Z
计算机元年增加毫秒数后为:1970-01-02T00:00:00Z
计算机元年增加秒数后为:1970-01-02T00:00:00Z
获取的秒值为:440000000
从时间对象获取的Instant实例为:2022-04-13T08:40:44.438Z

4.2 LocalDate类

LocalDate类仅用来表示日期。通常表示的是年份和月份。

两种获取日期对象的方法,即now()和of(int year,int month,int dayOfMonth)

//从一年、一个月和一天获得一个LocalDate的实例
LocalDate Date=LocalDate.of(2020,12,12);

//从默认时区的系统时钟获取当前的日期
LocalDate now1=LocalDate.now();

LocalDate的常用方法

【案例】

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class test8 {
    public static void main(String[] args)throws Exception{
        //获取日期和时间
        LocalDate now=LocalDate.now();
        LocalDate of=LocalDate.of(2015, 12, 12);
        System.out.println("1.LocalDate的获取及格式化的相关方法-------");
        System.out.println("从LocalDate实例获取的年份为:"+now.getYear());
        System.out.println("从LocalDate实例获取的月份:"+now.getMonthValue());
        System.out.println("LocalDate实例获取当天在本月的第几天:"+now.getDayOfMonth());
        //    下面这句报错,也不知道为什么
        //System.out.println("将获取到的LocalDate实例格式化为:"+now.format(DateTimeFormatter.ofPattern("yyyy年mm月dd日")));

        System.out.println("2.LocalDate判断的相关方法----------");
        System.out.println("判断日期of是否在now之前:"+of.isBefore(now));
        System.out.println("判断日期of是否在now之后:"+of.isAfter(now));
        System.out.println("判断日期of和now是否相等:"+now.equals(of));
        System.out.println("判断日期of是否是闰年:"+of.isLeapYear());
        //给出一个符合默认格式要求的日期字符串
        System.out.println("3.LocalDate解析以及加减操作的相关方法-------");
        String dateStr="2020-02-01";
        System.out.println("把日期字符串解析为日期对象后为:"+LocalDate.parse(dateStr));
        System.out.println("将LocalDate实例年份加1为:"+now.plusYears(1));
        System.out.println("将LocalDate实例天数减10为:"+now.minusDays(10));
        System.out.println("将LocalDate实例指定年份为2014:"+now.withYear(2014));
        }
    }

【运行结果】 

1.LocalDate的获取及格式化的相关方法-------
从LocalDate实例获取的年份为:2022
从LocalDate实例获取的月份:4
LocalDate实例获取当天在本月的第几天:13
2.LocalDate判断的相关方法----------
判断日期of是否在now之前:true
判断日期of是否在now之后:false
判断日期of和now是否相等:false
判断日期of是否是闰年:false
3.LocalDate解析以及加减操作的相关方法-------
把日期字符串解析为日期对象后为:2020-02-01
将LocalDate实例年份加1为:2023-04-13
将LocalDate实例天数减10为:2022-04-03
将LocalDate实例指定年份为2014:2014-04-13

4.3 LocalTime类与LocalDateTime

LocalTime类用来表示时间,通常表示的是小时、分钟、秒

【案例】

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test8 {
    public static void main(String[] args)throws Exception{
        //获取当前时间,包含毫秒数
        LocalTime time=LocalTime.now();
        LocalTime of=LocalTime.of(9, 23, 23);
        System.out.println("从LocalTime获取的小时为:"+time.getHour());
       
        System.out.println("将获取到的LocalTime实例格式化为:"+time.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        System.out.println("判断时间of是否在now之前:"+of.isBefore(time));
        System.out.println("将时间字符串解析为时间对象后为:"+LocalTime.parse("12:15:30"));
        System.out.println("从LocalTime获取当前时间,不包含毫秒数:"+time.withNano(0));
        }
    }

【运行结果】

可以看出LocalTime类的方法的使用与LocalDate基本一样

从LocalTime获取的小时为:21
将获取到的LocalTime实例格式化为:21:03:26
判断时间of是否在now之前:true
将时间字符串解析为时间对象后为:12:15:30
从LocalTime获取当前时间,不包含毫秒数:21:03:26

LocalDateTime类是LocalDate类和LocalTime类的综合,它既包括日期,也包括时间,通过查看API可以知道,LocalDateTime类中的方法包含了LocalDate类与LocalTime类的方法。

需要注意的是:LocalDateTime默认的格式是2020-02-29T21:23:26.774,与人们经常使用的格式不太符合,下面提供转换的方法:

【运行代码】

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test8 {
    public static void main(String[] args)throws Exception{
        //获取当前年月日,时分秒
       LocalDateTime now=LocalDateTime.now();
       System.out.println("格式化前的日期时间为:"+now);
       System.out.println("将目标LocalDateTime转换为相应的LocalDate实例:"+now.toLocalDate());
       System.out.println("将目标LocalDateTime转换为相应的LocalTime实例:"+now.toLocalTime());

       //指定格式
       DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy年mm月dd日hh时mm分ss秒");
       System.out.println("格式化后的日期时间为:"+now.format(ofPattern));
        }
    }

【运行结果】

格式化前的日期时间为:2022-04-13T21:23:04.577
将目标LocalDateTime转换为相应的LocalDate实例:2022-04-13
将目标LocalDateTime转换为相应的LocalTime实例:21:23:04.577
格式化后的日期时间为:2022年23月13日09时23分04秒

4.4 Period和Duration类

简单的时间计算方法

4.4.1 Duration类

Duration类基于时间值,其作用范围是天、时、分、秒、毫秒和纳秒

Duration类的常用方法

between(Temporal startInclusive,Temporal end Exclusive) //获得一个Duration表示两个时间对象之间的持续时间

toDays() //将时间转换为以天为单位
toHours() //将时间转换为以小时为单位
toMinutes() //将时间转换为以分钟为单位
toMillis() //将时间转换为以毫秒为单位
toNanos() //将时间转换为以纳米为单位

【常用方法的使用案例】

通过between()方法计算出start和end的时间间隔

import java.time.Duration;
import java.time.LocalTime;

public class test8 {
    public static void main(String[] args)throws Exception{
        LocalTime start=LocalTime.now();
        LocalTime end=LocalTime.of(23, 13, 23);
        Duration duration=Duration.between(start, end);
        //间隔的时间
        System.out.println("时间间隔为:"+duration.toNanos()+"纳秒");
        System.out.println("时间间隔为:"+duration.toMillis()+"毫秒");
        System.out.println("时间间隔为:"+duration.toHours()+"小时");
        }
    }

【运算结果】

时间间隔为:5903866000000纳秒
时间间隔为:5903866毫秒
时间间隔为:1小时

4.4.2 Period类

Period主要用于计算两个日期的间隔,与Duration相同,也是通过between计算日期间隔

,并提供了获取年月日的3个常用方法:getYear() , getMonths() , getDays().

【案例】

import java.time.LocalDate;
import java.time.Period;

public class test8 {
    public static void main(String[] args)throws Exception{
        LocalDate birthday=LocalDate.of(2018, 12, 12);
        LocalDate now=LocalDate.now();
        //计算两个日期的时间间隔
        Period between=Period.between(birthday, now);
        System.out.println("时间间隔为:"+between.getYears()+"年");
        System.out.println("时间间隔为:"+between.getMonths()+"月");
        System.out.println("时间间隔为:"+between.getDays()+"天");
        
        }
    }

【运行结果】

时间间隔为:3年
时间间隔为:4月
时间间隔为:1天

5. 包装类

Java语言中不能把基本的数据类型作为对象来处理,每种基本类型都有对应的包装类

基本类型对应的包装类

基本数据类型===>>对应的包装类
byte-->Byte
char-->Character
int-->Integer
short-->Short
long-->Long
float-->Float
double-->Double
boolean-->Boolean

【案例】

以int类型的包装类Integer为例

public class test8 {
    public static void main(String[] args)throws Exception{
        int a=20;
        Integer in=a; //自动装箱
        System.out.println(in);
        
        int l=in;//自动拆箱
        System.out.println(l);
       
        
        }
    }

 【运行结果】

20
20

Integer类特有的方法

Integer valueOf(int i) //返回一个表示指定的int值的Integer实例

Integer valueOf(String s) //返回保存指定的String值的Integer对象

int parseInt(String s) //将字符串参数作为有符号的十进制整数进行解析

intValue() //将Integer类型的值以int类型返回

【案例】

public class test8 {
    public static void main(String[] args)throws Exception{
        Integer num = new Integer(20); //手动装箱
        int sum=num.intValue()+10; //手动拆箱
        System.out.println("将Integer类型的值转换为int类型后与10求和为:"+sum);
        System.out.println("返回表示10的Integer实例为:"+Integer.valueOf(10));
        int w=Integer.parseInt("20")+32;
        System.out.println("将字符串转换为整数为:"+w);
        }
    }

【运行结果】

将Integer类型的值转换为int类型后与10求和为:30
返回表示10的Integer实例为:10
将字符串转换为整数为:52

 6.正则表达式

在程序开发过程中,会对一些字符串做各种限制,例如生活中常见的注册时输入的邮箱、手机号等,一般都会有长度、格式等限制,这些限制就是正则表达式实现的。

6.1 元字符

常见的正则表达式元字符

6.2 Pattern类和Matcher类

Java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现,所以想要使用正则表达式,首先要学会这两个类的使用方法。

6.2.1 Pattern类

Patter用于创建一个正则表达式,也可以说,创建一个匹配模式,它的构造方法是私有的,不可直接创建,但可以通过Pattern.complie(String regex)简单工厂方法创建一个正则表达式,具体代码如下:

Pattern p=Pattern.compile("\\w");

Pattern在正则表达式的应用中比较广泛,所以灵活使用Pattern类是非常重要的。下面介绍Pattern类的常用方法:

split(CharSequence input)  //将给定的输入列表分成这个模式的匹配

Matcher matcher(CharSequence input) //提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持

Static boolean matches(String regex,CharSequence input) //编译给定的正则表达式,并尝试匹配给定的输入。

【案例】

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test8 {
    public static void main(String[] args)throws Exception{
        Pattern p=Pattern.compile("\\d+");
        String[] str=p.split("我的QQ是:456456我的电话是:0532214我的邮箱是:aaa@aaa.com");
        System.out.println("是否匹配Pattern的输入模式"+Pattern.matches("\\d+","2223"));
        System.out.println("是否匹配Pattern的输入模式"+Pattern.matches("\\d+","2223aa"));
        Matcher m=p.matcher("22bb23");
        System.out.println("返回该Match对象是由哪个Pattern对象创建的,即p为:"+m.pattern());
        System.out.println("将给定的字符串分割成Pattern模式匹配为:");
        for(int i=0;i<str.length;i++){
            System.out.print(str[i]+" ");
        }

        }
    }

将第五行代码通过compile()方法创建一个正则表达式,在第6~7行代码通过split()方法将字符串按照给定的模式进行分割,并返回命名为str的数组。第8~11行代码通过matches()方法判断是否匹配Pattern的输入模式,第12~14行代码通过pattern()方法判断Matcher对象是由哪个Pattern对象创建的,第15~18行代码通过for循环输出str数组。 

【运行结果】

是否匹配Pattern的输入模式true
是否匹配Pattern的输入模式false
返回该Match对象是由哪个Pattern对象创建的,即p为:\d+
将给定的字符串分割成Pattern模式匹配为:
我的QQ是: 我的电话是: 我的邮箱是:aaa@aaa.com

 6.2.2 Matcher类

Matcher类用于给定的Pattern实例的模式控制下进行字符串的匹配工作,同理,Matcher的构造方法也是私有的,不能直接创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例。

几个Matcher类的常用方法

boolean matches()  //对整个字符串进行匹配,只有整个字符串都匹配才返回True
boolean looking At() //对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回True
boolean find() //对字符串进行匹配,匹配到的字符串可以在任何位置
int end() //返回最后一个字符匹配后的偏移量
string group() //返回匹配到的子字符串
int start() //返回匹配到的子字符串在字符串中的索引位置

 【案例】

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test8 {
    public static void main(String[] args)throws Exception{
        Pattern p=Pattern.compile("\\d+");
        Matcher m1=p.matcher("22bb23");
        System.out.println("字符串是否匹配:"+m1.matches());

        Matcher m2=p.matcher("2223");
        System.out.println("字符串是否匹配:"+m2.matches());
        System.out.println("对前面的字符串匹配结果为:"+m1.lookingAt());

        Matcher m3=p.matcher("aa2223");
        System.out.println("对前面的字符串匹配结果为:"+m3.lookingAt());

        //System.out.println("是否匹配Pattern的输入模式"+Pattern.matches("\\d+","2223"));
        //System.out.println("是否匹配Pattern的输入模式"+Pattern.matches("\\d+","2223aa"));
        m1.find(); //返回True
        System.out.println("字符串任何位置是否匹配:"+m1.find());
        m3.find(); //返回True
        System.out.println("字符串任何位置是否匹配:"+m3.find());

        Matcher m4=p.matcher("aabb");
        System.out.println("字符串任何位置是否匹配:"+m4.find());

        Matcher m5=p.matcher("aaa2223bb");
        m5.find();
        System.out.println("上一个匹配的起始索引:"+m5.start());
        System.out.println("最后一个字符匹配后的偏移量为:"+m5.end());
        System.out.println("匹配到的字符串:"+m5.group());

        }
    }

在第6~9行代码通过matches()方法判断字符串是否匹配;第10~13行代码通过lookingAt()方法对前面的字符串进行匹配;第14~20行代码通过find()方法对字符串进行匹配,匹配到的字符串可以在任何位置;第21行代码通过start()方法得出一个字符匹配的起始索引;第22行代码通过end()方法得出最后一个字符匹配后的偏移量;第23行代码通过group()方法得出匹配到的字符串。 

【运行结果】

字符串是否匹配:false
字符串是否匹配:true
对前面的字符串匹配结果为:true
对前面的字符串匹配结果为:false
字符串任何位置是否匹配:false
字符串任何位置是否匹配:false
字符串任何位置是否匹配:false
上一个匹配的起始索引:3
最后一个字符匹配后的偏移量为:7
匹配到的字符串:2223

6.3 String类对正则表达式的支持

String类提供了3个方法支持正则操作。

boolean matches(String regex)   //匹配字符串
String replaceAll(String regex,String replacement) //字符串替换
String[] split(String regex) //字符串拆分

【案例】

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test8 {
    public static void main(String[] args)throws Exception{
        String str="A1B22DDS34DSJ9D".replaceAll("\\d+", "_");
        System.out.println("字符替换后为:"+str);
        boolean te="321123as1".matches("\\d+");
        System.out.println("字符串是否匹配:"+te);
        String s [] ="SDS45d4DD4dDS88D".split("\\d+");
        System.out.println("字符串拆分为:");
        for(int i=0;i<s.length;i++){
            System.out.print(s[i]+" ");
        }

 
        }
    }

【运行结果】

字符替换后为:A_B_DDS_DSJ_D
字符串是否匹配:false
字符串拆分为:
SDS d DD dDS D

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值