第四节 Java常用API

1. 字符串操作API(String和String Buffer)

不同的字符串之间我们可以用“+”号去连接,形成一个新的字符串。当一个不是字符串的通过加号连接,会进行自动的转换为字符串。

1.1 String类

利用String创建字符串的三种方式:
public class Stringop {
    public static void main(String[] args) {
        String str1="第一种方法创建字符串";
        String str2=new String("第二种方法去创建字符串");
        char[] ch={'a','b','c'};
        String str3=new String(ch);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}

1.1.1 String类常用方法

public class Example01 {
    public static void main(String[] args) {
        //定义一个字符串
        String str1="abcdefga";
        //1.返回指定字符或字符串在字符串中第一次出现的索引
        System.out.println(str1.indexOf("ab"));
        System.out.println(str1.indexOf('a'));
        System.out.println(str1.indexOf(97));
        //2.返回指定字符或字符串在字符串中最后一次出现的索引
        System.out.println(str1.lastIndexOf('a'));
        System.out.println(str1.lastIndexOf(97));
        System.out.println(str1.lastIndexOf("ab"));
        //3.返回指定索引处的字符
        System.out.println(str1.charAt(0));
        //4.判断字符串是否以指定字符串结尾
        System.out.println("str1是以ga结尾吗?"+str1.endsWith("ga"));
        //5.返回这个字符串的长度
        System.out.println("字符串的长度为:"+str1.length());
        //6.判断字符串是否与指定字符串值相等
        System.out.println(str1.equals("aaa"));
        //7.判断某字符串是否为空
        System.out.println(str1.isEmpty());
        //8.判断字符串是否以某字符串开头
        System.out.println(str1.startsWith("a"));
        //9.判断字符串是否包含某字符串
        System.out.println(str1.contains("abcd"));
        //10.将所有字符串中所有字符转换为小写
        System.out.println(str1.toLowerCase());
        //11.将所有字符串中的所有字符都转换为大写
        System.out.println(str1.toUpperCase());
        //12.将数值类型的变量转换为字符串
        System.out.println(String.valueOf(23));
        //13.将字符串转换为字符数组
        char[] ch;
        ch=str1.toCharArray();
        System.out.println(ch.toString());
        //14.将字符串中的字符串序列进行替换
        String str2=str1.replace("ab","aa");
        //15.根据参数值进行分割
        String[] strarr;
        strarr=str1.split("bc");
        System.out.println(strarr);
        //16.从指定位置进行截取
        System.out.println(str1.substring(2));
        System.out.println(str1.substring(2,4));
        //17.去除字符串首尾的空格
        System.out.println(str1.trim());
    }
}

注意:在这里面的equals()方法和==的区别:
equals()比较的是两个字符串的值是否相等,而==比较的是两个字符串的内存地址。

        String str3="abcd";
//        String str4=new String("abcd");(1)
        String str4="abcd";//(2)
        System.out.println(str3==str4);//(1)false,(2)true
        System.out.println(str3.equals(str4));//(1)true (2)true

1.2 StringBuffer类

与String类的区别:
(1)在Java中String类是final类型,所以使用String定义的字符串是一个常量,一旦创建,内容和长度是不可以改变的,如果要对一个字符串进行修改,则只能创建一个新的字符串。而StringBuffer它的内容和长度是可以改变的,当我们操作这个字符串就是在操作这个字符串容器。
(2)String重写了Object类的equals()方法,而StringBuffer没有重写,Object里的equals()方法与Object里面的不一样需要注意,String里面的只比较值,而StringBuffer比较的是内存地址与==一样,
(3)String对象中的字符串可以用“+”号连接,而StringBuffer中的字符串不可以用“+”号连接。

常见的方法使用:

public class Example02 {
    public static void main(String[] args) {
        StringBuffer strbuf=new StringBuffer("abcdefg");
        System.out.println("返回字符串对象:"+strbuf.toString());
        //进行添加
        System.out.println(strbuf.append('h'));
        //进行在指定位置插入元素
        System.out.println(strbuf.insert(strbuf.length()-1,'i'));
        //进行删除指定位置字符
        System.out.println(strbuf.deleteCharAt(strbuf.length()-1));
        //删除指定范围的字符串
        System.out.println(strbuf.delete(strbuf.length()-1,strbuf.length()));
        //指定字符串范围进行替换
        System.out.println(strbuf.replace(0,1,"cc"));
        //修改指定位置的字符
        strbuf.setCharAt(0,'a');
        System.out.println(strbuf);
        strbuf.reverse();
        System.out.println(strbuf);
    }
}

StringBuffer 与StringBuilder的区别:
StringBuilder同样可以操作字符串,并且方法与StringBuffer类似,但是与StringBuffer不同的是StringBuffer是线程安全的,而StringBuilder不是线程安全的,但是它的性能会比较高一些。

2.System类与Runtime类

2.1 System类

这个类主要用来操作系统的一些相关属性和方法。

System常用方法:
(1)static void exit(int status):用来终止Java虚拟机运行,status值不为0表示非正常终止。我们通过状态码可以看看我们程序是否有错误出现
(2)static void gc():运行垃圾回收器
(3)static native long currentTimeMillis():返回当前据1970年1月1号的毫秒数

4)arraycopy(Object src,int srcPos,Object dest,int destPos,int length)的使用:用来copy数组。
int[] srcArry={1,2,3,4};
int[] destArry={5,6,7,8};
System.arraycopy(srcArry,0,destArry,0,3);
结果就变成了,{1,2,3,8}
(5)static Properties getProperties():获取当前系统属性
public class Example04 {
    public static void main(String[] args) {
        Properties properties=System.getProperties();
        System.out.println(properties);
        //获取所有系统属性的属性名,返回Set对象
        Set<String> propertyNames=properties.stringPropertyNames();
        for(String key:propertyNames){
            //System的另一个方法获得指定键的系统属性值
            String value=System.getProperty(key);
            System.out.println(key+"--->"+value);
        }
    }
}

2.2 Runtime类

用于表示Java虚拟机运行时的状态,它用于封装Java虚拟机进程。每次使用java命令启动Java虚拟机都会对应一个Runtime实例,并只有一个实例,应用程序会通过该实例与其运行时的环境相连。应用程序不能创建自己的Runtime实例,但是我们可以通过Runtime.getRuntime()方法来获取Runtime对象

Runtime的使用示例:

public class RuntimeExam {
    public static void main(String[] args) {
        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");
    }
}

其中里面有一个exec()方法用来执行DOS命令,返回一个Process对象
使用如下:

public class RuntimeExec {
    public static void main(String[] args) throws InterruptedException, IOException {
        Runtime rt=Runtime.getRuntime();
        //打开记事本
        Process process=rt.exec("notepad.exe");
        Thread.sleep(3000);
        //关闭记事本
        process.destroy();
    }
}

3. Math类和Random类

3.1 Math类

Math所有的方法都是静态的,它的构造方法被private修饰了,所以不可以创建Math对象。

//Math里面的两个常量值:PI和E,一个代表Π,一个代表e
abs(数值)//计算绝对值
sin(数值)//计算正弦值
cos(数值)//计算余弦值
tan(数值)//计算正切值
sqrt(数值)//计算平方根
cbrt(数值)//计算立方根
pow(数值1,数值2)//求乘方
ceil(数值)//大于参数的最小整数(返回的是double类型的)
floor(数值)//小于参数的最大整数(返回的是double类型的)
round(数值)//四舍五入后的结果(返回的整数)
max(数值1,数值2..)//求最大值
min(数值1,数值2...)//求最小值
random()//随机生成一个大于等于0.0,小于1.0的随机值

3.2 Random类

用来随机生成数字
两个构造方法:
(1)Random():空参构造方法,每次实例化都会生成不同的随机数
(2)Random(long seed):当seed相同时,每次实例化对象生成相同的随机数。(用来创建多个Random实例对象产生相同序列的随机数)

常用方法:
(1)boolean nextBoolean():随机生成boolean类型的随机数
(2)double nextDouble():随机生成double类型的随机数(0.0到1.0之间)
(3)Float nextFloat():随机生成Float类型的随机数(0.0到1.0之间)
(4)int nextInt():随机生成int类型的随机数
(5)int nextInt(int n):随机生成[0,n)之间int类型的随机数
(6)long nextLong():随机生成long类型的随机数

4. 包装类

包装类就是基本数据类型对应的引用数据类型
除了int的包装类型是Integer,char的包装类是Character,其他的包装类都是基本数据类型的首字母大写即可,比如:byte的包装类型为Byte。
在包装类和基本数据类型进行转换时有自动装箱和自动拆箱的概念。
自动装箱:将基本数据类型赋值给包装类型
自动拆箱:将包装类对象直接赋值给一个对应的基本数据类型。

4.1 基本数据类型、基本数据类型包装类以及字符串之间的转换

(1)通过引用数据类型字符串String类的valueOf()可以将八种基本数据类型转换为对应的字符串类型
(2)通过八种包装类的静态方法valueOf()可以将对象将对应的基本数据类型转换为包装类,也可以将变量内容匹配的字符串转换为对应的包装类(Character除外)例如:我们可以通过以下的形式int a=Integer.valueOf(“123”);将字符串转换为它对应的整数类型
(3)通过八种包装类的有参构造方法可以将基本数据类型转换为包装类,也可以将变量内容匹配的字符串转换为对应的包装类(Character包装类除外)例如:int a=new Integer(“123”);
(4)通过8种包装类的静态方法parseXxx()可以将变量内容匹配的字符串转换为对应的基本数据类型。
例如:
double a=Double.parseDouble(“123.4”);
(5)包装类都重写了toString()方法以字符串的形式返回被包装的基本数据类型值。例如:String a=new Integer(12).toString()

5. 日期与时间类

5.1 Date类

在JDK8之后使用的就比较少了(设计的时候没有考虑到国际化的问题,现在被Calendar类取代),主要使用的两个构造方法为:
(1)Date():用来创建当前日期时间的Date对象
(2)Date(long date):用来创建指定时间的Date对象,参数date表示的是从1970年1月1日以来的毫秒数(时间戳)

5.2 Calendar类

它是一个抽象类,不能实例化,通过其静态方法getInstance()来得到Calendar对象。

  1. 常用方法:
    (1)int get(int field):返回指定日历字段的值
    (2)void add(int field,int amount):为指定日历字段增加或减去时间量
    (3)void set(int field,int value):为指定字段设定值
    (4)void set(int year,int month,int date):设置年月日
    (5)void set(int year,int month,int date,int hourOfDay,int minute,int second):设置年月日,时分秒。
    (6)getTime():获得一个Date对象
    (7)setTime():设置一个返回类型为Calendar对象类型的,参数要为Date类型
    其中:field字段是用Calendar里面的YEAR、MONTH、DATE、HOUR、MINUTE、SECOND常量表示。month是从0到11这点要注意。
    Date对象和Calendar对象通过上面的getTime()和setTime()方法可以进行相互之间的转换。

  2. 容错模式(lenient)和非容错模式(non-lenient)
    当处于容错模式时,数值可以超出允许范围的值,当我们使用get()方法去获取某个值的时候,Calendar会自动的重新去计算所有字段的值,将字段的值去标准化,默认的是容错模式,如果设置为非容错模式了,当我们的数值超过允许的范围之后会抛异常。我们通过Calendar里面的setLenient(false)来设置为非容错模式。

  3. JDK 8 的日期与时间类
    为了满足更多的需求,JDK 8增加了一个java.time包,在这个包里有了更多的操作日期和时间的类。
    这些类的使用方法如下:

public class JDK8Calendar {
    public static void main(String[] args) {
        //1.使用Clock获取指定时区的当前时间
        Clock clock=Clock.systemUTC();
        System.out.println("获取UTC时区转换的当前时间:"+clock.instant());
        System.out.println("获取UTC时区转换的毫秒数:"+clock.millis());
        //2.使用Duration,主要用里面的ofXxx()方法获取指定的时间的小时、分钟、秒数等
        Duration duration=Duration.ofDays(1);
        System.out.println("一天等于:"+duration.toHours()+"小时");
        System.out.println("一天等于:"+duration.toMinutes()+"分钟");
        System.out.println("一天等于:"+duration.toMillis()+"秒");
        //3.使用Instant,通过静态方法now()获取当前时间,通过plusXxx()方法来增加,minusXxx()方法来减少
        Instant instant=Instant.now();
        System.out.println("获取UTC时区的当前时间为:"+instant);
        System.out.println("当前时间一小时后的时间为:"+instant.plusSeconds(3600));
        System.out.println("当前时间一个小时前的时间:"+instant.minusSeconds(3600));
        //4.使用LocalDate,通过静态方法now()获取不带时间的日期,通过plusXxx()和minusXxx()方法加减
        LocalDate localDate=LocalDate.now();
        System.out.println("现在日期是:"+localDate);
        //5.使用LocalTime,通过静态方法now()获取不带日期的时间
        LocalTime localTime=LocalTime.now();
        System.out.println(localTime);
        //6.使用LocalDateTime,通过静态方法now()获取日期时间,通过plusXxx()和minusXxx()方法来加减
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println(localDateTime);
        LocalDateTime times=localDateTime.plusDays(1).plusHours(3).plusMinutes(30);
        System.out.println(times);
        //7.使用Year、YearMonth、MonthDay
        Year year=Year.now();
        System.out.println("当前年份"+year);
        YearMonth yearMonth=YearMonth.now();
        System.out.println("当前年月"+yearMonth);
        MonthDay monthDay=MonthDay.now();
        System.out.println("当前的月日"+monthDay);
        //8.使用ZoneId,表示一个时区
        ZoneId zoneId=ZoneId.systemDefault();
        System.out.println("当前系统的默认时区为:"+zoneId);
    }
}

注意:如果我们这里通过clock.instant()来获取时间会和通过Instant.now()来获取的时间相差8个小时,因为Instant默认使用的UTC(世界标准时间),而通过clock.instant()来获取的时间是CST(中国标准时间)。
其中还有DayOfWeek类用来定义星期一到星期日,是个枚举类,Month也是枚举类用来定义一月到12月。

5.3 格式化类

目的:获得我们想要的格式输出的时间和日期。

5.3.1 DateFormat类

它是一个抽象类,不能被实例化,但是它提供了一系列的方法来获取实例对象。它用来格式化日期。

常用方法:

方法声明功能描述
static DateFormat getDateInstance()创建默认语言风格的日期格式器
static DateFormat getDateInstance(int style)创建指定风格的日期格式器
static DateFormat getDateTimeInstance创建默认风格的日期/时间格式器
static DateFormat getDateTimeInstance(int dateStyle,int timeStyle)用于创建指定风格的日期/时间
String format(Date date)将一个Date格式化为日期/时间字符串
Date parse(String source)将给定字符串解析成一个日期

注意:前四个方法用来获取实例化对象,其中DateFormat里面有四个常量值用于作为参数传递给方法。FULL、LONG、MEDIUM、SHORT,FULL表示完整格式,LONG表示长格式、MEDIUM表示普通格式,SHORT表示短格式。
我们可以利用parse()方法将字符串格式化成我们想要格式的Date对象。

5.3.2 SimpleDateFormat类

解决了DateFormat对象的parse()方法将字符串解析为日期的时候,需要输入固定格式的字符串不够灵活,他是DateFormat的子类,可以用new去创建,创建实例化对象时,构造方法接受一个表示日期格式模板的字符参数。
使用如下:

public class SimpleDateFormatDemo {
    public static void main(String[] args) {
        SimpleDateFormat sdf=new SimpleDateFormat("Gyyyy年MM月dd日:今天是yyyy年的第D天,E");
        System.out.println(sdf.format(new Date()));
        //其中的G表示公元,y表示年,d表示日,M表示月,D表示天,E表示星期。
    }
}

解析比DateFormat灵活体现在下面:

        SimpleDateFormat sdf2=new SimpleDateFormat("yy/MM/dd");
        Date date=sdf2.parse("21/03/02");
        System.out.println(date);

5.3.3 DateTimeFormatter类

用来将日期、时间对象格式化成字符串和将特定格式的字符串解析成日期、时间对象。相当于DateFormat和SimpleDateFormat合体。

获得DateTimeFormatter对象的三种方式:
(1)使用静态常量创建:在DateTimeFormatter类中包含大量的静态常量,如ASIC_ISO_DATE、ISO_LOCAL_DATE、ISO_LOCAL_TIME等
(2)使用不同风格的枚举值来创建:在FormatStyle类中定义了FULL、LONG、MEDIUM和SHORT四个枚举值。
(3)根据模式字符串创建
使用如下:

public class DateTimeFormatterDemo {
    public static void main(String[] args) {
        LocalDateTime date=LocalDateTime.now();
        //1.使用常量创建
        DateTimeFormatter dtf=DateTimeFormatter.ISO_DATE_TIME;
        System.out.println(dtf.format(date));
        //2.使用不同风格的枚举值来创建
        DateTimeFormatter dtf2=DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        System.out.println(dtf2.format(date));
        //3.使用模式字符串来创建
        DateTimeFormatter dtf3=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(date.format(dtf3));
    }
}

格式化字符串可以通过以下两种方式:
(1)调用DateTimeFormatter的format(TemporalAccessor temporal),参数是TemporalAccessor类型的接口,主要实现类有LocalDate、LocalDateTime。
(2)调用LocalDate、LocalDateTime等日期对象的format(DateTimeFormatter formatter)方法。

使用DateTimeFormatter将指定格式的字符串解析成日期、时间对象,可以通过日期、时间对象所提供的parse(CharSequence text,DateTimeFormatter formatter)方法来实现。

使用方式如下:

public class DateTimeFormatterParseDemo {
    public static void main(String[] args) {
        //定义两种日期格式的字符串
        String str1="2020-01-12 14:23:33";
        String str2="2020年01月12日 14时23分33秒";
        //定义解析所用容器
        DateTimeFormatter formatter1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter2=DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        //使用LocalDateTime的parse()方法执行解析
        LocalDateTime ldt1=LocalDateTime.parse(str1,formatter1);
        LocalDateTime ldt2=LocalDateTime.parse(str2,formatter2);
        //输出结果
        System.out.println(ldt1);
        System.out.println(ldt2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值