JavaSE(二)

文章目录


前言

java基础(Java SE)。【自用】
在线中文文档
JavaSE(一)


一、类相关

1、类变量(静态变量)和类方法(静态方法)

访问修饰符 static 数据类型 数据名; //类变量
  • 满足访问修饰符的访问权限和范围。
  • static 变量是同一个类所有对象共享。
  • static 类变量,在类加载的时候就生成了。

------------------------------------------------------------------------

访问修饰符 static 数据返回类型 方法名(){ //类方法
}
  • 满足访问修饰符的访问权限和范围。
  • 类方法中不能使用this和super,普通方法可以。
  • 类方法只能访问静态变量和静态方法。
  • 普通方法既可以访问普通变量(方法),又可以访问静态变量(方法)。

2、main方法语法

  1. java虚拟机需要调用类的main()方法,所有该方法的访问权限必须是public。
  2. java虚拟机在执行main()方法时不必创建对象,所以该方法必须是static。
  3. 该方法接收String类型的数组参数,该数组中保存执行java命令时传递给所运行的类的参数。
  4. java 执行的程序名 参数1 参数2 参数3。

3、代码块

[修饰符]{
	代码;
};
  • 修饰符是可选项,但是要写只能写 static。
  • 代码块分为两类,使用static修饰的叫静态代码块,没有static修饰的,叫普通代码块。
  • static代码块也叫静态代码块,作用就是对类进行初始化,而且它随着类的加载而执行,并且只会执行一次。如果是普通代码块,每创建一个对象,就执行。
  • 普通的代码块,在创建对象实例时,会被隐式的调用,被创建一次,就调用一次。如果只是使用类的静态成员,普通代码块并不会执行。
  • 类被加载的三种情况: 1.创建对象实例时。 2.创建子类对象实例,父类也会被加载。 3.使用类的静态成员时(静态属性和静态方法)。
  • 创建一个对象,类的调用顺序:1.静态代码块和静态属性初始化。 2.普通代码块和普通属性的初始化。 3.构造方法。
  • 继承关系下的调用顺序:1.父类的静态代码块和静态属性。 2.子类的静态代码块和静态属性。 3.父类的普通代码块和普通属性初始化。 4.父类的构造器。 5.子类的普通代码块和普通属性初始化。 6.子类的构造方法。
  • 静态代码块只能直接调用静态成员(静态属性和静态方法),普通代码块可以调用任意成员。

4、单例模式

定义:采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。

饿汉式

  1. 构造器私有化。
  2. 类的内部创建对象。
  3. 向外暴露一个静态的公共方法。
public class Test {

    public static void main(String[] args) {
        A aa = A.getInstance();
        System.out.println(aa);
    }
}

class A{
    private String name;

    private static A a = new A("xxxxx");

    private A(String name) {
        this.name = name;
    }

    public static A getInstance(){
        return a;
    }
}

-----------------------------------------------------------

懒汉式:(存在线程安全问题。)

  1. 构造器私有化。
  2. 定义一个静态属性对象。
  3. 向外暴露一个静态的公共方法,返回对象。
public class Test {

    public static void main(String[] args) {
        A aa = A.getInstance();
        System.out.println(aa);
    }
}

class A{
    private String name;

    private static A a = null;

    private A(String name) {
        this.name = name;
    }

    public static A getInstance(){
        if (a == null) {
            a = new A("xxxxx");
        }
        return a;
    }
}

5、final关键字

final可以修饰类、属性、方法和局部变量。

使用需求

  1. 当不希望类被继承时,可以用final修饰。
  2. 当不希望父类的某个方法被子类覆盖/重写时,可以用final关键字修饰。
  3. 当不希望类的某个属性的值被修改,可以用final修饰。
  4. 当不希望某个局部变量别修改,可以使用final修饰。

注意事项

  1. final修饰的属性又叫常量,一般用XX_XX_XX来命名。
  2. final修饰的属性在定义时,必须赋初值,并且以后不能再修改,赋值可以在如下位置之一:1.定义时。 2.在构造器中。 3.在代码块中。
  3. 如果final修饰的属性是静态的,则初始化的位置只能是: 1.定义时。 2.在静态代码块。(不能在构造器中赋值。)
  4. final类不能继承,但是可以实例化对象。
  5. 如果类不是final类,但是含有final方法,则该方法虽然不能重写,但是可以被继承。
  6. 若一个类已经是final类了,就没有必要再将方法修饰成final方法。
  7. final不能修饰构造方法。
  8. final和static往往搭配使用,效率更高,不会导致类加载,底层编译器做了优化处理。
  9. 包装类(Integer,Double,Float,Boolean)都是final类,String也是final类,都不能被继承。

6、抽象类(abstract)

当父类的某些方法,需要声明,但是又不确定如何实现时,可以将其声明为抽象方法,那么这个类就是抽象类;当使用抽象方法时,这个类就必须声明成抽象类(加abstract)。

访问修饰符 abstract 返回类型 方法名(); //子类来实现具体细节。

注意事项:

  1. 抽象类不能被实例化。
  2. 抽象类不一定包含abstract方法,即抽象类可以没有abstract方法。
  3. 一旦类包含了abstract方法,则这个类必须声明为abstract。
  4. abstract只能修饰类和方法,不能修饰属性和其他的。
  5. 抽象类可以有任意成员。
  6. 抽象方法不能有主体,即不能实现。
  7. 如果一个类继承了抽象类,则它必须实现抽象类的所有抽象方法,除非它自己也声明为abstract类。
  8. 抽象方法不能使用private、final、static来修饰。

7、接口(interface)

interface 接口名{
	属性;
	方法; // 1.抽象方法  2.静态方法  3.默认方法,例如defaul public void sum(){代码块;}
}


class 类名 implements 接口名{
	属性;
	方法;
	必须实现的接口的抽象法方法;
}

注意事项:

  1. 在JDK7.0前,接口里的所有方法都没有方法体。
  2. 在JDK8.0后,接口类可以有静态方法,默认方法(default),即接口中可以有方法的具体实现。
  3. 接口不能被实例化。
  4. 接口中所有方法是public方法,接口中抽象方法可以不用abstract修饰。
  5. 一个普通类实现接口,就必须将该接口的所有方法都实现。
  6. 抽象类实现接口,可以不用实现接口的方法。
  7. 一个类同时可以实现多个接口。
  8. 接口中的属性,只能是final的,而且是public static final 修饰符。
  9. 接口中属性的访问形式:接口名.属性名
  10. 接口不能继承其他的类,但可以继承多个别的接口。interface A extends B,C{}
  11. 接口的修饰符只能是public和默认,这点和类的修饰符是一样的。

继承的价值主要在于:解决代码的复用性和可维护性。
接口的价值主要在于:设计,设计好各种规范(方法),让其它类去实现这些方法,即更加的灵活。


8、内部类

定义:一个类的内部又完整的嵌套了另一个类结构。被嵌套的类称为内部类,嵌套其他类的类称为外部类。内部类最大的特点就是可以直接访问私有属性,并且可以体现类与类之间的包含关系。类中五大构成:属性、方法、构造器、代码块、内部类。

class Outer{ //外部类
	class Inner{ // 内部类
	
	}
}

class Other{ // 外部其他类
}

内部类1
内部类2

8.1、局部内部类

  1. 可以直接访问外部类的所有成员,包含私有的。
  2. 不能添加访问修饰符(因为它的地位就是一个局部变量,局部变量是不能使用修饰符的),但是可以使用final修饰,因为局部变量也可以使用final。
  3. 作用域:仅仅在定义它的方法或代码块中。
  4. 局部内部类–访问—>外部类的成员。【访问方式:直接访问。】
  5. 外部类–访问—>局部内部类的成员。【访问方式:创建对象,再访问。】
  6. 外部其他类–不能访问—>局部内部类。(因为局部内部类地位是一个局部变量。)
  7. 如果外部类和局部内部类的成员重名时,默认遵循就近原则,如果想访问外部类的成员,使用外部类名.this.成员去访问。
public class Class_ {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.method();
    }
}


class Outer {
    private int num = 2;

    public void f1() {
    }

    public void method() {
        class Inner { //局部内部类,通常定义在方法中。
            private int num = 200;
            public void innerMethod() {
                f1();
                System.out.println("num=" + num); //遵循就近原则
                System.out.println("Outer的num=" + Outer.this.num);
            }
        }
        Inner inner = new Inner();
        inner.innerMethod();
    }
}

8.2、匿名内部类(只能用一次)

基本语法:

new/接口(参数列表){
	类体;
};

---------------------------------------------------------------------------

  1. 可以直接访问外部类的所有成员,包含私有的。
  2. 不能添加访问修饰符,因为它的地位就是一个局部变量。
  3. 作用域:仅仅在定义它的方法或代码块中。
  4. 匿名内部类–访问—>外部类成员。【访问方式:直接访问。】
  5. 外部其他类–不能访问—>匿名内部类。(因为匿名内部类地位是一个局部变量。)
  6. 如果外部类和内部类的成员重名时,默认遵循就近原则,如果想访问外部类的成员,使用外部类名.this.成员去访问。
public class AnonymousInner {
    public static void main(String[] args) {
        OuterAnony outerAnony = new OuterAnony();
        outerAnony.method();
    }
}

class OuterAnony{ //外部类
    private int num = 2;
    public void method(){
        /*  底层
        * class XXX implements A{
        *   @Override
            public void cry() {
                System.out.println("hello world!");
            }
        * }
        *
        * */
        A aa = new A(){ //匿名内部类,基于接口
            @Override
            public void cry() {
            	System.out.println(num);
                System.out.println("hello world!");
            }
        };
        aa.cry();
        System.out.println(aa.getClass()); //匿名内部类的类名

        /*  底层
        * class XXX extends Father{
        * }
        * */
        Father father = new Father("tom"){ //匿名内部类,基于类
            @Override
            public void test() {
                System.out.println("hello world@");
            }
        };
        father.test();
        System.out.println(father.getClass()); //匿名内部类的类名
    }
}

interface A{ //接口
    public void cry();
}

class Father{
    public Father(String name){ //构造器
    	System.out.println(name); 
    }

    public void test(){
    }
}

8.3、成员内部类

  1. 可以直接访问外部类的所有成员,包含私有的。
  2. 可以添加任意访问修饰符。
  3. 作用域和外部类的其他成员一样,为整个类体。
  4. 成员内部类—>访问—>外部类成员。
  5. 外部类—>访问—>成员内部类。(创建成员内部类对象,调用方法。)
  6. 外部其他类—>访问—>成员内部类
  7. 如果外部类和内部类的成员重名时,内部类访问的话,默认遵循就近原则,如果想访问外部类的成员,使用外部类名.this.成员去访问。
public class MemberInnerCass {
    public static void main(String[] args) {
        MemberOuter memberOuter = new MemberOuter();
        memberOuter.the();

        // 1.外部类调用成员内部类
        MemberOuter.MemberInner memberInner = memberOuter.new MemberInner();
        memberInner.say();

        // 2.外部类调用成员内部类
        MemberOuter.MemberInner inner = memberOuter.getInner();
        inner.say();

    }
}

class MemberOuter{
    private int num = 2;
    public String name = "李四";
    class MemberInner{ // 成员内部类
        public int num = 6;
        public void say(){
            System.out.println("xxxxxxx" + name);
            System.out.println(num);
            System.out.println(MemberOuter.this.num);
        }
    }

    public void the(){
        MemberInner memberInner = new MemberInner();
        memberInner.say();
    }

    public MemberInner getInner(){
        return new MemberInner();
    }
}

8.4、静态内部类

  1. 可以直接访问外部类的所有静态成员,包含私有的,但不能直接访问非静态成员。
  2. 可以添加任意访问修饰符。
  3. 作用域:同其他的成员,为整个类体。
  4. 静态内部类—>访问—>外部类。(直接访问所有静态成员。)
  5. 外部类—>访问—>静态内部类。(创建对象,再访问。)
  6. 如果外部类和静态内部类的成员重名时,静态内部类访问的话,默认遵循就近原则,如果想访问外部类的成员,使用外部类名.成员去访问。
public class StaticInnerClass {
    public static void main(String[] args) {
        StaticClass staticClass = new StaticClass();
        staticClass.hi();

        // 1.外部类访问静态内部类
        StaticClass.StaticInner staticInner = new StaticClass.StaticInner();
        staticInner.say();

        // 2.外部类访问静态内部类
        StaticClass.StaticInner inner = staticClass.getInner();
        inner.say();

        // 3.外部类访问静态内部类
        StaticClass.StaticInner inner_ = StaticClass.getInner_();
        inner_.say();

    }
}

class StaticClass{
    private int num = 2;
    private static String name = "李四";

    static class StaticInner{
        private static String name = "王五";
        public void say(){
            System.out.println("xxxxxx" + name);
            System.out.println(StaticClass.name);
        }
    }

    public void hi(){
        StaticInner staticInner = new StaticInner();
        staticInner.say();
    }

    public StaticInner getInner(){
        return new StaticInner();
    }

    public static StaticInner getInner_(){
        return new StaticInner();
    }
}


9、枚举类

  1. 当用enum关键字开发一个枚举类时,默认会继承Enum类。
  2. 传统的public static final Season SPRING = new Season(“春天”,“温暖”); 简化成SPRING(“春天”,“温暖”);
  3. 当使用无参构造器创建枚举对象,则实参列表和小括号可以省略。
  4. 当有多个枚举对象时,使用,间隔,最后一个分号结尾。
  5. 枚举对象必须放在枚举类的行首。
  6. enum类隐式继承Enum。
public class Enumeration {
    public static void main(String[] args) {
        System.out.println(Season.AUTUMN.getName());
        System.out.println(Season.AUTUMN.getDesc());
    }
}

enum Season{

    SPRING("春天","温暖"),WINTER("冬天","寒冷"),
    AUTUMN("秋天","凉爽"),SUMMER("夏天","炎热");

    private String name;
    private String desc;
    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }
}

12、注解(Annotation)

@interface 是注解类,即也是一个类。

10.1、@Override

定义:限定某个方法,是重写父类方法,该注解只能用于方法。


10.2、@Deprecated

定义:用于表示某个程序元素(类、方法等)已过时。


10.3、@SuppressWarnings

定义:抑制编译器警告。
用法:@SuppressWarnings({“all”});

10.4、4个元注解

10.4.1、Retention

定义:指定注解的作用范围。只用于修饰一个注解定义,用于指定该注解可以保留多长时间,@Retention包含一个RetentionPolicy类型的成员变量,使用@Retention必须为该value成员变量指定值。

  • RetentionPolicy.SOURCE:编译器使用后,直接丢弃这种策略的注解。
  • RetentionPolicy.CLASS:编译器将把注释记录在class文件中,当运行Java程序时,JVM不会保留注释。
  • RetentionPolicy.RUNTIME:编译器将把注释记录在class文件中,当运行Java程序时,JVM会保留注释,程序可通过反射获取该注释。

10.4.2、Target

定义:指定注解可以在哪些地方使用。(属性、方法、类…)


10.4.3、Documented

定义:用于指定被该元注解修饰的注解类将被javadoc工具提取成文档,即在生成文档时,可以看到该注解。
备注:定义为Documented的注解必须设置Retention值为RUNTIME。


10.4.4、Inherited

定义:子类会继承父类注解。


二、异常

异常
Exception

1、运行时异常

  1. NullPointerException:空指针异常
  2. ArithmeticException:数字运算异常
  3. ArrayIndexOutOfBoundsException:数组下标越界异常
  4. ClassCastException:类型转换异常
  5. NumberFormatException:数字格式不正确异常

2、编译时异常

  1. SOLException:操作数据库相关异常
  2. IOException:操作文件相关异常
  3. FileNotFoundException:文件不存在异常
  4. ClassNotFoundException:加载类不存在异常
  5. EOFException:操作文件,到文件末尾,发生异常
  6. IllegalArguementException:参数异常

3、异常处理机制

  • try-catch-finally:程序员在代码中捕获发生的异常,自行处理。
  • throws:将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者是JVM。

3.1、try-catch-finally

try {
            代码块;
        } catch (Exception e){ // 发生异常才执行。
            System.out.println(e);
        } finally { // 不管是否有异常发生,始终要执行。
            代码块;
}

3.2、throws

  1. 子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常类型的子类型。
  2. 对于运行时异常,程序中如果没有处理,默认就是throws的方式处理。
  3. 对于编译时异常,程序必须处理,比如try-catch或者throws。
  4. 在throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws。
public class Exception_ {
    public static void main(String[] args) throws Exception{
        System.out.println("hello world!");
    }
}

3.3、自定义异常

  1. 自定义异常类继承Exception或RuntimeException。
  2. 如果继承Exception,属于编译异常。
  3. 如果继承RuntimeException,属于运行异常。(一般来说,继承RuntimeException)
public class Exception_ {
    public static void main(String[] args) {
        int age = 810;
        if (!(age >= 18 && age <= 120)){
            throw new EgException("年龄需要在 18-120之间");
        }
        System.out.println("你的年龄范围正常。");
    }
}
class EgException extends RuntimeException{
    public EgException(String message) {
        super(message);
    }
}

throw和throws的区别


三、常用类(Java8手册)

1、包装类

  1. 引用类型–包装类。
  2. 有了类的特点,就可以调用类中的方法。
  3. 除Boolean、Character外,其余包装类的父类是Number。

包装类

1.1、包装类(引用类型)和String类型的相互转换

public class WrapperVSString {
    public static void main(String[] args) {
        // 包装类---->String类型
        Integer num = 10;
        // 方式1
        String num_1 = num.toString();
        // 方式2
        String num_2 = String.valueOf(num);
        // 方式3
        String num_3 = num + "";


        //String类型---->包装类
        // 方式1
        Integer num_4 = new Integer(num_1);
        // 方式2
        Integer num_5 = Integer.valueOf(num_2);
        // 方式3
        Integer num_6 = Integer.parseInt(num_3);
    }
}

1.2、Integer类和Character类的常用方法

public class IntegerAndCharacter {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE); // 返回最大值
        System.out.println(Integer.MIN_VALUE); // 返回最小值
        
        
        System.out.println(Character.isDigit('2')); // 判断是不是数字
        System.out.println(Character.isLetter('a')); // 判断是不是字母
        System.out.println(Character.isUpperCase('A')); // 判断是不是大写
        System.out.println(Character.isLowerCase('a')); // 判断是不是小写
        
        
        System.out.println(Character.isWhitespace('a')); // 判断是不是空格
        System.out.println(Character.toUpperCase('a')); // 转成大写
        System.out.println(Character.toLowerCase('A')); // 转成小写
        
    }
}

2、String

String本质就是char value[] 数组存储。
String类图

2.1、String创建刨析

public class String_ {
    public static void main(String[] args) {
        String s = "tom"; // 方式一
        String t = new String("tom"); // 方式二
        
        /*
        * 方式一:先从常量池查看是否有tom数据空间,如果有,直接指向;
        * 如果没有则重新创建,然后指向。s最终指向的是常量池的空间地址。
        * 
        * 方式二:先在堆中创建空间,里面维护了value属性,指向常量池的tom空间。
        * 如果常量池没有tom,重新创建,如果有,直接通过value指向。最终指向
        * 的是堆中的空间地址。
        * 
        * */
    }
}

2.2、String特性

public class String_ {
    public static void main(String[] args) {
        String res = "ab" + "cd";
        System.out.println(res == "abcd"); // 一

        String a = "ab";
        String b = "cd";
        String res_dy = a + b;
        System.out.println(res_dy == "abcd"); // 二
        
        /*
         * 一:常量相加,看的是常量池。
         * 
         * 二:变量相加,看的是堆。
         * 
         * */
    }
}
public class String_ {
    public static void main(String[] args) {
        String rhw = "abcd";
        ABS ab = new ABS();
        ab.num = 5555;
        ab.str = "xxx";
        System.out.println(ab.num); // 输出:5555
        System.out.println(ab.str); // 输出:xxx
        System.out.println(rhw); // 输出:abcd
        ab.change(ab,rhw);
        System.out.println(ab.num); // 输出:22
        System.out.println(ab.str); // 输出:abc
        System.out.println(rhw); // 输出:abcd
        // 注意String类型输出--->rhw

    }
}

class ABS{
    int num = 2;
    String str = "ab";
    public void change(ABS abs, String st){
        abs.num = 22;
        abs.str = "abc";
        st = "xxx_";
    }
}

2.3、String常用方法

String类是保存字符串常量的。每次更新都需要重新开辟空间,效率较低,因此Java设计者提供StringBuilderStringBuffer来增强String的功能并提高效率。
String方法

  • equals:判断内容是否相等(区分大小写)。
  • equalsIgnoreCase:判断内容是否相等(忽略大小写)。
  • length:获取字符的个数,字符串的长度。
  • indexOf:获取字符在字符串中第一次出现的索引,索引从0开始,如果找不到,返回-1。
  • lastIndexOf:获取字符在字符串中最后一次出现的索引,索引从0开始,如果找不到,返回-1。
  • substring:截取指定范围的子串。
  • trim:去前后空格。
  • charAt:获取某索引处的字符,注意不能使用Str[index]方式。
  • toUpperCase:全部改为大写。
  • toLowerCase:全部改为小写。
  • concat:拼接字符串。
  • replace:替换字符串中的字符。
  • split:分割字符串。
  • toCharArray:转换成字符数组。
  • compareTo:比较两个字符串的大小,前者大,则返回正数;后者大,返回负数;如果相等,返回0。
  • format:格式字符串。%s 字符串;%c 字符;%d 整型;%.2f 浮点型。

3、StringBuffer

3.1、基本介绍

  • java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删。
  • 很多方法和String是相同的,但StringBuffer是可变长度的。
  • StringBuffer是一个容器。
  • StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高。

StringBuffer


3.2、构造器

StringBufferStruct


3.3、StringBuffer和String相互转换

public class StringTest {
    public static void main(String[] args) {

        // String ---> StringBuffer
        String s = "hello";
        // 方式1
        // 返回的才是StringBuffer对象,对s本身没有影响。
        StringBuffer b1 = new StringBuffer(s);
        // 方式2
        StringBuffer b2 = new StringBuffer();
        b2.append(s);


        // StringBuffer ---> String
        // 方式1
        String r = b1.toString();
        // 方式2
        String g = new String(b2);
    }
}


3.4、StringBuffer方法

  • append:追加
  • delete(start,end):删
  • replace(start,end,str):改
  • indexOf:查
  • insert(index,str):插
  • length():获取长度

4、StringBuilder

4.1、基本介绍

  • 是一个可变的字符序列。此类提供一个与StringBuffer兼容的API,但不保证同步(StringBuilder不是线程安全的。)。该类被设计用作StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer要快。
  • 在StringBuilder上的主要操作是append和insert方法,可重载这些方法,以接受任意类型的数据。
  • StringBuilder的方法,没有做互斥的处理,即没有synchronized关键字,因此在单线程的情况下使用。

StringBuilder


4.2、构造器

StringBuilderStruct


4.3、StringBuilder和StringBuffer比较

  1. StringBuffer和StringBuilder非常相似,均代表可变的字符序列,而且方法也一样。
  2. String:不可变字符序列,效率低,但是复用率高。
  3. StringBuffer:可变字符序列、效率较高(增删)、线程安全。
  4. StringBuilder:可变字符序列、效率最高、线程不安全。

4.4、String、StringBuilder和StringBuffer的选择

  1. 如果字符串存在大量的修改操作,一般使用StringBuffer或StringBuilder。
  2. 如果字符串存在大量的修改操作,并在单线程的情况,使用StringBuilder。
  3. 如果字符串存在大量的修改操作,并在多线程的情况,使用StringBuffer。
  4. 如果字符串很少修改,被多个对象引用,使用String,比如配置信息等。

5、Math

5.1、基本介绍

Math类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。


5.2、常用方法

  1. abs:绝对值
  2. pow:求幂
  3. ceil:向上取整
  4. floor:向下取整
  5. round:四舍五入
  6. sqrt:求开方
  7. random:求随机数。[0,1)
  8. max:最大值
  9. min:最小值

6、Arrays

  1. toString:返回数组的字符串形式。
  2. sort:排序,包含自然排序和定制排序。
  3. binarySearch:通过二分搜索法进行查找,要求必须排好序。
  4. copyOf:数组元素的复制
  5. fill:数组元素的填充
  6. equals:比较两个数组元素内容是否完全一致
  7. asList:将一组值,转换成list
public class ArraysMethods {
    public static void main(String[] args) { // 封装,继承,多态 YYDS
        // 1.返回数组的字符串形式。
        System.out.println(Arrays.toString(new int[]{1, 2, 3}));

        // 2.排序,自然排序
        Integer arr[] = {1,-2,8,0,45};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        // 2.排序,定制排序
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        System.out.println(Arrays.toString(arr));
        // 2.封装,继承,多态感悟之后的想法。
        Arrays.sort(arr,new ArraysSortCustom());
        System.out.println(Arrays.toString(arr));

        // 3.通过二分搜索法进行查找,要求必须排好序。
        arr = new Integer[]{-2, 0, 1, 8, 45};
        int res = Arrays.binarySearch(arr,1);
        System.out.println(res);

        // 4.数组元素的复制
        Integer[] item = Arrays.copyOf(arr,arr.length);
        System.out.println(Arrays.toString(item));

        // 5.数组元素的填充
        Integer[] num = new Integer[]{9,6,2};
        Arrays.fill(num,888);
        System.out.println(Arrays.toString(num)); // [888, 888, 888]

        // 6.比较两个数组元素内容是否完全一致
        boolean equ = Arrays.equals(arr,num);
        System.out.println(equ);

        // 7.将一组值,转换成list
        List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println(asList);
    }
}

class ArraysSortCustom implements Comparator{

    @Override
    public int compare(Object o1, Object o2) {
        int o11 = (int)o1;
        int o12 = (int)o2;
        return o12 -o11;
    }
}

7、System

  1. exit:退出当前程序
  2. arraycopy:复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组
  3. currentTimeMillens:返回当前距离1970-1-1的毫秒数
  4. gc:运行垃圾回收机制 System.gc()
public class SystemClass {
    public static void main(String[] args) {

        // 1.退出当前程序
        System.exit(0); // 0表示正常退出状态

        // 2.复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组
        int[] src = {1,2,3};
        int[] dest = new int[3];
        System.arraycopy(src,0,dest,0,3);
              // 源数组  开始拷贝位置  目标数组  拷贝到目标数组哪个位置  拷贝多少个数据
        System.out.println(Arrays.toString(dest));

        // 3.返回当前距离1970-1-1的毫秒数
        long l = System.currentTimeMillis();
        System.out.println(l);

        // 4.运行垃圾回收机制
        System.gc();
    }
}


8、BigInteger、BigDecimal

8.1、BigInteger

BigInteger适合保存比较大的整数。

public class BigClass {
    public static void main(String[] args) {

        BigInteger bigInteger = new BigInteger("222222222222222222222222222222222222");
        System.out.println(bigInteger);

        // 不能直接进行 + - * / 运算
        // 1.加法
        BigInteger bigInteger2 = new BigInteger("10");
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);

        // 2.减法
        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);

        // 3.乘法
        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);

        // 4.除法
        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);
    }
}

8.2、BigDecimal

BigDecimal适合保存精度更高的浮点型(小数)。

public class BigDecimal_{

    public static void main(String[] args) {

        BigDecimal bigDecimal = new BigDecimal("2222.4444444444");
        System.out.println(bigDecimal);

        // 不能直接进行 + - * / 运算
        // 1.加法
        BigDecimal bigDecimal1 = new BigDecimal("2222.5646454646");
        BigDecimal add = bigDecimal.add(bigDecimal1);
        System.out.println(add);

        // 2.减法
        BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
        System.out.println(subtract);

        // 3.乘法
        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
        System.out.println(multiply);

        // 4.除法 (有可能抛出异常。)-->解决办法:指定精度位数。
        BigDecimal divide = bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING);
        System.out.println(divide);
    }
}


9、Date、Calendar、LocalDate…

9.1、第一代日期类

  1. Date:精确到毫秒,代表特定的瞬间。
  2. SimpleDateFormat:格式和解析日期的类。
public class DateClass {
    public static void main(String[] args) throws ParseException {

        // 1.获取当前系统时间
        Date date = new Date();
        date.getTime(); // 获取某个时间对应的毫秒数

        // 2.通过指定毫秒数得到时间
        Date date1 = new Date(8621521);
        System.out.println(date1);

        // 3.格式和解析日期的类。
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
        String format = simpleDateFormat.format(date); // 将日期转换成指定格式的字符串
        System.out.println(format);

        // 4.把一个格式化的String 转为对应的 Date
        String s = "2023年02月17日 08:15:04 星期五";
        Date sDate = simpleDateFormat.parse(s);
        System.out.println(sDate);
    }
}

9.2、第二代日期类

  1. Calendar是一个抽象类,并且构造器是private的,可以通过 getInstance() 获取实例。
public class DateSecond{
    public static void main(String[] args) {
        
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);

        // 1.获取月份
        int s = calendar.get(Calendar.MONTH) + 1;

        // 2.获取日
        calendar.get(Calendar.DAY_OF_MONTH);

        // 3.获取小时
        calendar.get(Calendar.HOUR);
        calendar.get(Calendar.HOUR_OF_DAY); // 24小时进制

        // 4.获取分钟
        calendar.get(Calendar.MINUTE);

        // 5.获取秒
        calendar.get(Calendar.SECOND);

        // 6.获取年
        calendar.get(Calendar.YEAR);
    }
}

9.3、第三代日期类

  1. LocalDate:日期
  2. LocalTime:时间
  3. LocalDateTime:日期时间
  4. DateTimeFormatter:格式日期类
  5. Instant:时间戳,类似于Date,提供一系列和Date类转换的方式。
class DateThird{
    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();
        // LocalDate.now();  LocalTime.now();
        System.out.println(localDateTime);

        // 1.获取年
        localDateTime.getYear();

        // 2.获取月份,数字
        localDateTime.getMonthValue();

        // 3.获取月份,英文
        localDateTime.getMonth();

        // 4.获取日
        localDateTime.getDayOfMonth();

        // 5.获取小时
        localDateTime.getHour();

        // 6.获取分钟
        localDateTime.getMinute();

        // 7.获取秒
        localDateTime.getSecond();

        // 8.DateTimeFormatter:格式日期类
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss E");
        String s = dateTimeFormatter.format(localDateTime);
        System.out.println(s);

        // 9.Instant:时间戳
        // Instant ---> Date
        Instant now = Instant.now();
        System.out.println(now);
        Date date = Date.from(now);
        // Date ---> Instant
        Instant instant = date.toInstant();
    }
}

四、集合

1、集合框架体系

  1. 可以动态保存任意多个对象,使用比较方便。
  2. 提供了一系列方便的操作对象的方法:add、remove、set、get等。
  3. 使用集合添加,删除新元素的示意代码简洁。

Collection框架图
Map框架图


2、Collection(单列集合,存放的是值。)

Collection体系图

2.1、Collection接口的常用方法

2.1.1、常用方法

Collection接口常用方法,以实现子类。

public interface Collection<E> extends Iterable<E> {}
  1. add:添加单个元素
  2. remove:删除指定元素
  3. contains:查找元素是否存在
  4. size:获取元素个数
  5. isEmpty:判断是否为空
  6. clear:清空
  7. addAll:添加多个元素
  8. containsAll:查找多个元素是否都存在
  9. removeAll:删除多个元素
public class Collection_ {

    @SuppressWarnings("all")
    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();

        // 1.添加元素
        arrayList.add("tom");
        arrayList.add(20);
        arrayList.add(true);
        System.out.println(arrayList);

        // 2.获取某个元素
        System.out.println(arrayList.get(0));

        // 3.删除某个元素
        arrayList.remove(1);
        // 指定删除某个元素
        arrayList.remove(true);
        System.out.println(arrayList);

        // 4.查找某个元素
        boolean res = arrayList.contains("tom");
        System.out.println(res);

        // 5.获取元素个数
        System.out.println(arrayList.size());


        // 6.判断是否为空
        System.out.println(arrayList.isEmpty());

        // 7.清空
        arrayList.clear();
        System.out.println(arrayList);

        // 8.添加多个元素
        ArrayList arrayList1 = new ArrayList();
        arrayList1.add("红楼梦");
        arrayList1.add(155);
        arrayList.addAll(arrayList1);
        System.out.println(arrayList);

        // 9.查找多个元素是否存在
        System.out.println(arrayList.containsAll(arrayList1));
        
        // 10.删除多个元素
        arrayList.removeAll(arrayList1);
        System.out.println(arrayList);
    }
}

2.1.2、遍历元素 - 使用Iterator(迭代器)
  1. Iterator对象称为迭代器,主要用于遍历Collection集合中的元素。
  2. 所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象,即可以返回一个迭代器。
  3. Iterator仅用于遍历集合,Iterator本身并不存放对象。
public class Collection_Iterator {

    @SuppressWarnings("all")
    public static void main(String[] args) {
        Collection collection = new ArrayList();
        collection.add(new Book("三国演义","罗贯中",10.1));
        collection.add(new Book("红楼梦","tom",30.5));
        collection.add(new Book("水浒传","jack",23.6));

        Iterator iterator = collection.iterator();
        // 迭代器---> 快捷键:itit
        // 显示所有快捷键:ctrl + j
        while (iterator.hasNext()){
            Object next = iterator.next();
            System.out.println(next);
        }
        
        // 若要再次遍历,需要重置迭代器
        iterator = collection.iterator();
        System.out.println(iterator.next());
    }
}

class Book{
    private String name;
    private String author;
    private double price;

    public Book() {
    }

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}


2.1.3、遍历元素 - 使用增强for循环

for(元素类型 元素名:集合名或数组名){
访问元素
}

// 增强for循环 底层仍然是迭代器
// 快捷方式:I
for (Object book : collection) { // 接 2.1.2、代码。
            System.out.println(book);
        }

2.2、List

List接口是Collection接口的子接口。

  1. List集合类中元素有序(即添加顺序和取出顺序一致)且可重复。
  2. List集合中的每个元素都有其对应的顺序索引,即支持索引。
  3. List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
  4. List接口的实现类常用的包括:ArrayList、LinkedList、Vector。

2.2.1、List接口常用的方法
public class List_ {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("tom");
        list.add("jack");
        list.add("jierui");
        // 1.在index = 1的位置插入一个对象
        list.add(1,"hello");
        System.out.println(list);

        // 2.从index位置开始将arrayList所有元素添加进来
        List arrayList = new ArrayList();
        arrayList.add("world");
        arrayList.add("hw");
        list.addAll(1,arrayList);
        System.out.println(list);

        // 3.获取指定index位置的元素
        System.out.println(list.get(2));

        // 4.返回在当前集合中首次出现的位置
        int hw = list.indexOf("hw");
        System.out.println(hw);

        // 5.返回在当前集合中最后出现的位置
        int last = list.indexOf("hw");
        System.out.println(last);

        // 6.移除指定index位置的元素,并返回此元素
        Object remove = list.remove(0);
        System.out.println(remove);

        // 7.设置指定index位置的元素,相当于替换
        Object hm = list.set(2, "hm");
        System.out.println(hm);

        // 8.返回从fromIndex到toIndex位置的集合([)-->前闭后开)
        List list1 = list.subList(0, 2);
        System.out.println(list1);
    }
}


2.2.2、List的三种遍历方式

list接口的实现类都可使用以下三个方法。

		// 代码接 2.2.1 
        // 1.遍历方式一:使用iterator迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);
        }

        // 2.遍历方式二:使用增强for循环
        for (Object object: list) {
            System.out.println(object);
        }

        // 3.遍历方式三:使用普通for
        for (int i = 0; i <list.size() ; i++) {
            Object o = list.get(i);
            System.out.println(o);
        }

2.2.3、ArrayList
  1. ArrayList可以加入null,并且多个。
  2. ArrayList是由数组来实现数据存储的。
  3. ArrayList基本等同于Vector,除了ArrayList是线程不安全(执行效率高),在多线程下,不建议使用ArrayList。
/**	 transient;表示该属性不会被序列化
 4. 1.ArrayList中维护了一个Object类型的数组elementData。源码:transient Object[] elementData;
 5. 2.当创建对象时,如果使用的是无参构造器,则初始elementData容量为0,第一次添加,则扩容elementData为10,如需要再次扩容,则扩容elementData为1.5倍。
 6. 3.当创建对象时,如果使用的是指定容量的构造器,则初始elementData容量为指定大小,如果需要扩容,则直接扩容elementData为1.5倍。
 7. 4.当添加元素时,先判断是否需要扩容,如果需要扩容,则调用grow方法,否则直接添加元素到合适位置。
 8. */

2.2.4、Vector
  1. Vector底层也是一个对象数组,源码:protected Object[] elementData;
  2. Vector是线程同步的,即线程安全,Vector类的操作方法带有synchronized。
  3. 在开发中,需要线程同步安全时,考虑使用Vector。
/**	
 12. 1.Vector中维护了一个Object类型的数组elementData。源码:protected Object[] elementData;
 13. 2.当创建对象时,如果使用的是无参构造器,则初始elementData容量为10,如需要再次扩容,则扩容elementData为2倍。
 14. 3.当创建对象时,如果使用的是指定容量的构造器,则初始elementData容量为指定大小,如果需要扩容,则直接扩容elementData为2倍。
 15. */

2.2.5、LinkedList
  1. LinkedList底层实现了双向链表和双端队列特点。
  2. 可以添加任意元素(元素可以重复),包括null。
  3. 线程不安全,没有实现同步。
/** 
* 1.LinkedList底层维护了一个双向链表。
* 2.LinkedList中维护了两个属性first和last分别指向首节点和尾节点。
* 3.每个节点(Node对象)里面又维护了prev、next、item三个属性,其中通过prev指向前一个,通过next指向后一个节点。
* 4.所以LinkedList的元素的添加和删除,不是通过数组完成的,相对来说效率较高。
* */

public class ArrayList_ {
    @SuppressWarnings("all")
    public static void main(String[] args) {
       
        // 1.Java-->双向链表 jack-tom-hw
        Node jack = new Node("jack");
        Node tom = new Node("tom");
        Node hw = new Node("hw");
        jack.next = tom;
        tom.pre = jack;
        tom.next = hw;
        hw.pre = tom;
        Node first = jack; // 双向链表的头结点
        Node last = hw; // 双向链表的尾结点
        // 1.1从头到尾遍历
        while (true){
            if (first == null){
                break;
            }
            System.out.println(first);
            first = first.next;
        }
        // 1.2从尾到头遍历
        while (true){
            if (last == null){
                break;
            }
            System.out.println(last);
            last = last.pre;
        }
        // 1.3tom-hw 中间插入 smith 结果:jack-tom-smith-hw
        Node smith = new Node("smith");
        smith.next = hw;
        hw.pre = smith;
        tom.next = smith;
        smith.pre = tom;
        first = jack;

        // 2.LinkedList
        LinkedList linkedList = new LinkedList();
        // 2.1添加节点
        linkedList.add(3);
        linkedList.add("hw");
        // 2.2删除节点
        linkedList.remove();// 默认删除第一个节点
        System.out.println(linkedList);
        // 2.3修改某个节点
        linkedList.set(0,555);
        System.out.println(linkedList);
        // 2.4获取某一个节点
        Object o = linkedList.get(0);
        System.out.println(o);
        // 2.5.1遍历:iterator迭代器
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);
        }
        // 2.5.2遍历:增强for循环
        for (Object object : linkedList) {
            System.out.println(object);
        }
        // 2.5.3遍历:普通for循环
        for (int i = 0; i <linkedList.size() ; i++) {
            System.out.println(linkedList.get(i));
        }
    }
}

class Node{ // 表示双向链表的一个节点
    public Object item; // 存放数据
    public Node next; // 后一个节点
    public Node pre; // 前一个节点

    public Node(Object item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "Node name = " + item;
    }
}


2.2.6、List集合选择
  1. 如果改查操作多,选择ArrayList。
  2. 如果增删操作多,选择LinkedList。
  3. 一般来说,在程序中,80%-90%都是查询,因此大部分情况下选择ArrayList。
  4. 在一个项目中,根据业务灵活选择,也可能是这样:一个模块使用的是ArrayList,另一个模块使用的是LinkedList。

2.3、Set

和List接口一样,Set接口也是Collection的子接口,因此,常用方法和Collection接口一样。

  1. 无序(添加和取出的顺序不一致),没有索引。
  2. 不允许重复元素,所以最多包含一个null。
2.3.1、Set接口常用的方法

同Collection的遍历方式一样,因为Set接口是Collection接口的子接口。可以使用迭代器和增强for循环,但不能使用索引的方式来获取。

public class Set_ {

    @SuppressWarnings("all")
    public static void main(String[] args) {
        // 以Set接口的实现类 HashSet 来讲解Set接口的方法
        HashSet hashSet = new HashSet();
        hashSet.add("jack");
        hashSet.add("tom");
        hashSet.add("smith");
        hashSet.add("jack");
        hashSet.add(null);
        hashSet.add(null);
        System.out.println(hashSet);

        // 1.遍历 - 迭代器
        Iterator iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);
        }

        // 2.遍历 - 增强for循环
        for (Object object: hashSet) {
            System.out.println(object);
        }
        
        // 3.删除某个元素
        hashSet.remove(null);
        System.out.println(hashSet);
    }
}


2.3.2、HashSet
  1. HashSet实现了Set接口。
  2. HashSet实际上是HashMap,HashMap底层是数组+链表+红黑树。
  3. 可以存放null值,但是只能有一个null。
  4. HashSet不保证元素是有序的,取决于hash后,再确定索引的结果。
  5. 不能有重复元素/对象。
 /**  HashSet扩容机制
* 1.HashSet底层是HashMap
* 2.添加一个元素时,先得到hash值,然后转成索引值。
* 3.找到存储数据表table,看这个索引位置是否已经存放的有元素。
* 4.如果没有,直接加入。
* 5.如果有,调用equals比较,如果相同,就放弃添加,如果不相同,则添加到最后。
* 6.在java8中,如果一条链表的元素个数到达TREEIFY_THRESHOLD(默认8),
*   并且table的大小 >= MIN_TREEIFY_CAPACITY(默认64),就会进行树化(红黑树)。
* */

// 底层核心源码
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
    HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        HashMap.Node<K,V> e; K k;
        if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof HashMap.TreeNode)
            e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

2.3.3、LinkedHashSet
  1. LinkedHashSet是HashSet的子类。
  2. LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组+双向链表。
  3. LinkedHashSet根据元素的hashCode值来决定元素的存储位置,同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的。
  4. LinkedHashSet不允许添加重复元素。

3、Map(双列集合,存放的是键值对 :K-V。)

Map体系图

  1. Map与Collection并列存在。用于保存具有映射关系的数据。
  2. Map中的key 和 value 可以是任何引用类型的数据,会封装到HashMap$Node对象中。
  3. Map中的key 不允许重复,原因和HashSet一样。
  4. Map中的value可以重复。
  5. Map的key可以为null,value也可以为null,注意key为null,只能有一个,value为null,可以多个。
  6. 常用String类作为Map的key。
  7. key 和 value 之间存在单向一对一关系,即通过指定的key 总能找到对应的value。
  8. 一对key-value是放在一个Node中的,又因为Node实现了Entry接口,有些书上说一对key-value就是一个Entry。

3.1、Map接口的常用方法

  1. put:添加
  2. remove:根据键删除映射关系
  3. get:根据键获取值
  4. size:获取元素个数
  5. isEmpty:判断个数是否为0
  6. clear:清除
  7. containsKey:查找键是否存在
  8. keySet:获取所有的键
  9. entrySet:获取所有关系
  10. values:获取所有的值

3.2、Map三大遍历方式

public class Map_ {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("no1","tom");
        map.put("no2","jack");
        map.put("no1","junny");
        map.put(null,null);
        map.put(1,"啊啊啊啊");
        System.out.println(map);

        // 1.遍历:先取出所有的key,通过key取出对应的value
        Set set = map.keySet();
        // 1.1 增强for循环
        for (Object o :set) {
            System.out.println(map.get(o));
        }
        // 1.2 迭代器循环
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(map.get(next));
        }
        
        // 2.遍历:取出所有的values
        Collection values = map.values();
        // 2.1 增强for循环
        for (Object o:values) {
            System.out.println(o);
        }
        // 2.2 迭代器循环'
        Iterator iterator1 = values.iterator();
        while (iterator1.hasNext()) {
            Object next =  iterator1.next();
            System.out.println(iterator1);
        }
        
        // 3.遍历:通过EntrySet来获取k-v
        Set set1 = map.entrySet();
        // 3.1 增强for循环
        for (Object o :set1) {
            Map.Entry m = (Map.Entry)o;
            System.out.println(m.getValue());
        }
        // 3.2 迭代器循环
        Iterator iterator2 = set1.iterator();
        while (iterator2.hasNext()) {
            Object next =  iterator2.next();
            Map.Entry m = (Map.Entry)next;
            System.out.println(m.getValue());
        }

        // 获取某个value
        System.out.println(map.get(1));
    }
}

3.3、Hashtable

  1. 存放的元素是键值对:即k-v。
  2. Hashtable的键和值都不能为null。
  3. HashTable使用方法基本上和HashMap一样。
  4. HashTable是线程安全的,HashMap是线程不安全的。

3.4、Properties

  1. Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存数据。
  2. 它的使用特点和Hashtable类似。
  3. Properties还可以用于从xxx.properties 文件中,加载数据到Properties类对象,并进行读取和修改。
  4. 说明:xxx.properties文件通常作为配置文件,IO流具体讲。

4、集合选择

/** 集合选择
 * 1.先判断存储的类型(一组对象或一组键值对)
 * 2.一组对象:Collection接口
 *      允许重复:List
 *           增删多:LinkedList[底层维护了一个双向链表]
 *           改查多:ArrayList[底层维护Object类型的可变数组]
 *      不允许重复:Set
 *           无序:HashSet[底层是HashMap,维护了一个哈希表,即数组+链表+红黑树]
 *           排序:TreeSet
 *           插入和取出顺序一致:LinkedHashSet,维护数组+双向链表
 * 3.一组键值对:Map
 *           键无序:HashMap[底层是哈希表 jdk7:数组+链表 jdk8:数组+链表+红黑树]
 *           键排序:TreeMap
 *           键插入和取出顺序一致:LinkedHashMap
 *           读取文件:Properties
 *
 * */

5、Collections工具类

  1. Collections是一个操作Set、List和Map等集合的工具类。
  2. Collections中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作。
  3. reverse(List):反转List中元素的顺序。
  4. shuffle(List):对List集合元素进行随机排序。
  5. sort(List):根据元素的自然顺序对指定List集合元素按升序排序。
  6. sort(List,Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序。
  7. swap(List,int a, int b):将指定list集合中的a处元素和b处元素进行交换。
  8. Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素。
  9. Object max(Collection, Comparator):根据Comparator指定的顺序,返回给定集合中的最大元素。
  10. Object min(Collection): 根据元素的自然顺序,返回给定集合中的最小元素。
  11. Object min(Collection, Comparator):根据Comparator指定的顺序,返回给定集合中的最小元素。
  12. int frequency(Collection,Object):返回指定集合中指定元素的出现次数。
  13. void copy(List dest,List src):将src中的内容复制到dest中。
  14. boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换List对象的所有旧值。

五、泛型

  1. 泛型又称参数化类型,是jdk5.0出现的新特性,解决数据类型的安全性问题。
  2. 在类声明或实例化时只要指定好需要的具体的类型即可。
  3. java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException异常。
  4. 泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型或者是某个方法的返回值的类型,或者是参数类型。
public class generic_ {
    public static void main(String[] args) {
        Person<String> stringPerson = new Person<String>("hello");
        System.out.println(stringPerson.f());
    }
}

class Person<E> {
    E s;
    public Person(E s){
        this.s = s;
    }
    public E f(){
        return s;
    }
}

1、泛型语法

interface 接口{} 和 class 类<K,V>{}

  1. 其中,T,K,V不代表值,而是表示类型;类型参数是引用类型,不能是基本类型。
  2. 任意字母都可以。常用T表示,是Type的缩写。
  3. 在指定泛型具体类型后,可以传入该类型或者子类类型。
List<String> strings = new ArrayList<String>();
Iterator<String> iterable = strings.iterator();

2、自定义泛型

2.1、泛型类

class 类名<T,R...>{// ...表示可以有多个泛型
	成员;
}
  1. 普通成员可以使用泛型(属性、方法)。
  2. 使用泛型的数组,不能初始化。
  3. 静态方法中不能使用类的泛型。
  4. 泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)。
  5. 如果在创建对象时,没有指定类型,默认为Object。
public class DivGeneric {
    public static void main(String[] args) {
        Tiger<String, Integer, Double> Tiger = new Tiger<String, Integer, Double>();
        
    }
}

class Tiger<T,R,M>{
    String name;
    T t;
    R r;
    M m;

    public Tiger() {
    }

    public Tiger(String name, T t, R r, M m) {
        this.name = name;
        this.t = t;
        this.r = r;
        this.m = m;
    }
}


2.2、泛型接口

interface 接口名<T,R...>{
	
}
  1. 接口中,静态成员也不能使用泛型。
  2. 泛型接口的类型,在继承接口或者实现接口时确定。
  3. 没有指定类型,默认为Object。
public interface DivGenericInterface {
    public static void main(String[] args) {

    }
}

class CC implements IUsb<Object,Object>{

    @Override
    public Object get(Object o) {
        return null;
    }

    @Override
    public void hi(Object o) {

    }

    @Override
    public void run(Object r1, Object r2, Object u1, Object u2) {

    }
}

class BB implements IUsb<Integer,Float>{

    @Override
    public Float get(Integer integer) {
        return null;
    }

    @Override
    public void hi(Float aFloat) {

    }

    @Override
    public void run(Float r1, Float r2, Integer u1, Integer u2) {

    }
}

class AA implements IA{

    @Override
    public Double get(String s) {
        return null;
    }

    @Override
    public void hi(Double aDouble) {

    }

    @Override
    public void run(Double r1, Double r2, String u1, String u2) {

    }
}

interface IA extends IUsb<String,Double>{

}

interface IUsb<U,R>{
    R get(U u);
    void hi(R r);
    void run(R r1,R r2,U u1,U u2);
    // jdk8中,可以在接口中使用默认方法
    default R method(U u){
        return null;
    }
}

2.3、泛型方法

修饰符 <T,R...>返回类型 方法名(参数列表){

}
  1. 泛型方法,可以定义在普通类中,也可以定义在泛型类中。
  2. 当泛型方法被调用时,类型会确定。
  3. public void eat(E e){},修饰符后没有<T,R…>,eat方法不是泛型方法,而是使用了泛型。
public class DivGenericMethod {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        Car car = new Car();
        car.fly("tom",100);
        car.fly("tom",100.1);

        Fish<String, ArrayList> fish = new Fish<>();
        fish.hello(new ArrayList(),11.3f);

    }
}

class Car{
    public void run(){}
    public <T,R>void fly(T t,R r){ // 泛型方法
        System.out.println(t.getClass());
        System.out.println(r.getClass());
    }
}

class Fish<T,R>{
    public void run(){}
    public <U,M>void eat(U u,M m){ // 泛型方法
    }

    public void hi(T t){ //普通方法

    }

    public <K>void hello(R r,K k){
        System.out.println(r.getClass());
        System.out.println(k.getClass());
    }
}

3、泛型继承和通配符

  1. 泛型不具备继承性。
  2. <?>:支持任意泛型类型。
  3. <? extends A>:支持A类以及A类的子类,规定了泛型的上限。
  4. <? super A>:支持A类以及A类的父类,不限于直接父类,规定了泛型的下限。

4、JUnit

  1. JUnit是一个Java语言的单元测试框架。
  2. 多数Java的开发环境都已经集成了JUnit作为单元测试的工具。
public class JUnit_ {
    public static void main(String[] args) {
        // 传统测试 方法
        new JUnit_().hi();
        new JUnit_().hello();
    }

    @Test
    public void hi(){
        System.out.println("hi方法.....");
    }

    @Test
    public void hello(){
        System.out.println("hello方法.....");
    }
}

六、线程

1、前提(绘图及监听)

public class BallMove extends JFrame{
    MyPanel mp = null;
    public static void main(String[] args) {
        new BallMove();
    }

    public BallMove(){
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.addKeyListener(mp); // 开启监听
    }
}

class MyPanel extends JPanel implements KeyListener {

    int x = 10;
    int y = 10;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x,y,20,20);
    }

    @Override
    public void keyTyped(KeyEvent e) { // 字符输出

    }

    @Override
    public void keyPressed(KeyEvent e) { // 按下某个键
        System.out.println((char)e.getKeyCode());
        // 根据用户按下的不同键来处理小球的移动
        if (e.getKeyCode() == KeyEvent.VK_DOWN) { // KeyEvent.VK_DOWN-->向下箭头的code
            y++;

        } else if (e.getKeyCode() == KeyEvent.VK_UP){
            y--;
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
        }
        this.repaint(); // 面板重绘
    }

    @Override
    public void keyReleased(KeyEvent e) { // 松开某个键

    }
}


2、线程基本使用

线程结构图

2.1、继承Thread类,重写run方法

public class Thread01 {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.start();
    }
}

class Cat extends Thread{ // 继承了thread类,该类就可以当作线程使用
    int times = 0;
    @Override
    public void run() {
        while (true){
            System.out.println("我是一只小猫!");
            times++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (times == 21)
                break;
        }
    }
}

2.2、实现Runnable接口,重写run方法

public class Thread02 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Thread thread = new Thread(dog);
        thread.start();
    }
}

class Dog implements Runnable{
    int count = 0;

    @Override
    public void run() {
        while (true){
            System.out.println("小狗汪汪叫!  " +Thread.currentThread().getName());
            count++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 21)
                break;
        }
    }
}

2.3、继承Thread和实现Runnable的区别

  1. 从java的设计来看,通过继承Thread或者实现Runnable接口来创建线程本质上没有区别,从jdk帮助文档可以看到Thread类本身就实现了Runnable接口。
  2. 实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制。

3、线程方法

  1. setName:设置线程名称,使之与参数name相同。
  2. getName:返回该线程的名称。
  3. start:使该线程开始执行。
  4. run:调用线程对象run方法。
  5. setPriority:更改线程的优先级。
  6. getPriority:获取线程的优先级。
  7. sleep:在指定的毫秒数内让当前正在执行的线程休眠。
  8. interrupt:中断线程。
  9. yield:让出cpu,让其他线程执行,但礼让的时间不确定,也不一定会成功。
  10. join:线程插队。

4、线程生命周期

线程状态图

4.1、Synchronized

在多线程中,一些敏感数据不允许被多个线程同时访问,此时就使用同步访问技术,保证数据在任何时刻,最多有一个线程访问,以保证数据的完整性。

  1. synchronized(对象){ // 需要被同步代码 }
  2. public synchronized void m(){ // 需要被同步的代码 }

4.2、互斥锁

  1. 每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。
  2. 关键字synchronized来与对象的互斥锁联系。当某个对象用synchronized修饰时,表明该对象在任一时刻只能由一个线程访问。
  3. 同步的局限性:导致程序的执行效率要降低。
  4. 同步方法(非静态的)的锁可以是this,也可以是其他对象(要求是同一个对象)。
  5. 同步方法(静态的)的锁为当前类本身。(类名.class)

七、IO流

1、文件

文件

1.1、创建文件的三种方式

public class fileTest {
    public static void main(String[] args) {
        // create01();
        // create02();
        create03();
    }

    // 1. new File(String pathname)
    public static void create01(){
        String filePath = "g:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 2. new File(File parent,String child) // 父目录文件+子路径
    public static void create02(){
        File parentFile = new File("g:\\");
        String fileName = "news2.txt";
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 3. new File(String parent,String child) // 父目录+子路径
    public static void create03(){
        String parentPath = "g:\\";
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.2、常用的文件操作

public class fileMethods {
    public static void main(String[] args) {

    }

    // 一、获取文件的信息
    @Test
    public void info(){
        File file = new File("g:\\news3.txt");

        // 1.文件名
        System.out.println("文件名字:" + file.getName());

        // 2.文件绝对路径
        System.out.println("文件绝对路径:" + file.getAbsolutePath());

        // 3.文件父级目录
        System.out.println("文件父级目录:" + file.getParent());

        // 4.文件大小(字节)
        System.out.println("文件大小:" + file.length());

        // 5.文件是否存在
        System.out.println("文件是否存在:" + file.exists());

        // 6.是否为文件
        System.out.println("是否为文件:" + file.isFile());

        // 7.是否为目录
        System.out.println("是否为目录:" + file.isDirectory());
    }



    // 二、目录的操作和文件删除
    // mkdir:创建一级目录    mkdirs:创建多级目录   delete:删除空目录或文件

    // 判断文件是否存在,存在就删除
    @Test
    public void m1(){
        String filePath = "g:\\news3.txt";
        File file = new File(filePath);
        if (file.exists()){
            if (file.delete())
                System.out.println("success");
        }else {
            System.out.println("fail");
        }
    }

    // 判断目录是否存在,存在就删除
    @Test
    public void m2(){
        String filePath = "G:\\adada";
        File file = new File(filePath);
        if (file.exists()){
            if (file.delete())
                System.out.println("success");
        }else {
            System.out.println("fail");
        }
    }

    // 判断目录是否存在,不存在就创建
    @Test
    public void m3(){
        String filePath = "G:\\adada";
        File file = new File(filePath);
        if (file.exists()){
            System.out.println("存在");
        }else {
           if (file.mkdirs())
               System.out.println("success");
        }
    }
}

2、IO流原理及流的分类

2.1、原理

  1. I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。
  2. Java程序中,对于数据的输入/输出操作以 ” 流(stream) “ 的方式进行。
  3. java.io包下提供了各种 ” 流 “ 类和接口,用以获取不同种类的数据,并通过方法输入或输出数据。
  4. 输入input:读取外部数据到程序中。
  5. 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。

2.2、分类(IO流体系图)

  • 按操作数据单位不同分为:字节流(8bit)【适用二进制文件】,字符流(按字符)【使用文本文件】
  • 按数据的流向不同分为:输入流,输出流
  • 按流的角色不同分为:节点流,处理流/包装流

流分类
注:Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。


3、输入流

3.1、InputStream

InputStream


3.1.1、FileInputStream(文件输入流)

构造方法以及常用方法

@SuppressWarnings("all")
public class fileInputStreamTest {

    // 1.单个字节的读取
    @Test
    public void readFile01(){
        String filePath = "G:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readData = fileInputStream.read())!= -1){
                System.out.print((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 2.字节数组读取
    @Test
    public void readFile02(){
        String filePath = "G:\\hello.txt";
        int readLen = 0;
        byte[] buf = new byte[10];
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            while ((readLen = fileInputStream.read(buf))!= -1){
                System.out.print(new String(buf,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.1.2、BufferedInputStream(缓冲字节输入流)

BufferedInputStream


3.1.3、ObjectInputStream(对象字节输入流)[反序列化]
  1. 序列化就是在保存数据时,保存数据的值和数据类型。
  2. 反序列化就是在恢复数据时,恢复数据的值和数据类型。
  3. 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:1.Serializable(标记接口,没有方法,推荐。) 2.Externalizable(有方法需要实现。)
public class ObjectInputStreamTest {
    public static void main(String[] args) {
        // 序列化后保存的文件格式不是纯文本,而是按照它的格式来保存
        String filePath = "G:\\data.txt";
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(filePath));
            oos.write(100);
            oos.writeBoolean(true);
            oos.writeChar('H');
            oos.writeDouble(3.2);
            oos.writeUTF("hello world");
            oos.writeObject(new Dog("张三",3));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

class Dog implements Serializable{
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

	@Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.2、Reader

Reader

3.2.1、FileReader
  1. new FileReader(File/String)
  2. read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
  3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1
@SuppressWarnings("all")
public class ReaderTest {

    // 1.单个字符读
    @Test
    public void readData01(){
        String filePath = "G:\\hello.txt";
        FileReader fileReader = null;
        int res = 0;
        try {
            fileReader =  new FileReader(filePath);
            while ((res = fileReader.read()) != -1){
                System.out.print((char) res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 2.多个字符读
    @Test
    public void readData02(){
        String filePath = "G:\\hello.txt";
        FileReader fileReader = null;
        int readLen = 0;
        char[] data = new char[20];
        try {
            fileReader =  new FileReader(filePath);
            while ((readLen = fileReader.read(data)) != -1){
                System.out.print(new String(data,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.2.2、BufferedReader
public class BufferedReaderTest {
    public static void main(String[] args) {
        String filePath = "G:\\hello.txt";
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

3.2.3、InputStreamReader(转换流)

InputStreamReader是Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)。当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,建议将字节流转换成字符流。

public class transformationTest {
    public static void main(String[] args) {
        transformationIo();
    }

    /**
     * @description: 把 FileInputStream(字节流) 转换为 InputStreamReader(字符流)
     * @return: void
     */
    public static void transformationIo(){
        String filePath = "G:\\test.txt";
        InputStreamReader gbk = null;
        BufferedReader br = null;
        try {
            gbk = new InputStreamReader(new FileInputStream(filePath), "utf-8");
            br = new BufferedReader(gbk);
            try {
                System.out.println(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

3.3、PrintWriter

public class PrintWriterTest {
    public static void main(String[] args) {
//        PrintWriter printWriter = new PrintWriter(System.out);
//        printWriter.println("hello world!");
//        printWriter.close();

        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(new FileWriter("G:\\test.txt"));
            printWriter.print("你好啊,AI");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            printWriter.close();
        }

    }
}

4、输出流

4.1、OutputStream

OutPutStream

4.1.1、FileOutputStream(文件输出流)

fileoutputstream

public class fileOutPutStreamTest {

    /**
     * @description: 将数据写到文件,
     * 如果该文件不存在,则创建该文件。
     * @return: void
     */
    @Test
    public void writeFile(){
        FileOutputStream fileOutputStream = null;
        String filePath = "G:\\a.txt";
        try {
            // new FileOutputStream(filePath,true)  追加写入
            fileOutputStream = new FileOutputStream(filePath);// 会覆盖原先的内容
            // 1.单个字节写入
            fileOutputStream.write('H');

            // 2.字符串写入
            fileOutputStream.write("hello world".getBytes());

            // 3.部分字符串写入
            fileOutputStream.write("abcdefg".getBytes(),2,4);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.1.2、BufferedOutputStream

BufferedOutputStream


4.1.3、ObjectOutputStream[序列化]
public class ObjectOutputStreamTest {
    public static void main(String[] args) {
        String filePath = "G:\\data.txt";
        ObjectInputStream ois = null;
        int res = 0;
        try {
            ois = new ObjectInputStream(new FileInputStream(filePath));
            System.out.println(ois.readInt());
            System.out.println(ois.readBoolean());
            System.out.println(ois.readChar());
            System.out.println(ois.readDouble());
            System.out.println(ois.readUTF());
            System.out.println(ois.readObject());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

4.2、Writer

Writer

4.2.1、FileWriter
  1. new FileWriter(File/String):覆盖模式
  2. new FileWriter(File/String,true):追加模式
  3. write(int):写入单个字符
  4. write(char[]):写入指定数组
  5. write(char[],off,len):写入指定数组的指定部分
  6. write(string):写入整个字符串
  7. write(string,off,len):写入字符串的指定部分
@SuppressWarnings("all")
public class WriterTest {

    // 1.写入单个字符
    @Test
    public void write01(){
        FileWriter fileWriter = null;
        String filePath = "G:\\hello.txt";
        try {
            fileWriter = new FileWriter(filePath,true);
            fileWriter.write("H");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 2.写入指定数组
    @Test
    public void write02(){
        FileWriter fileWriter = null;
        String filePath = "G:\\hello.txt";
        char[] data = {'a','b','c','d','e'};
        try {
            fileWriter = new FileWriter(filePath,true);
            fileWriter.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 3.写入整个字符串
    @Test
    public void write03(){
        FileWriter fileWriter = null;
        String filePath = "G:\\hello.txt";
        try {
            fileWriter = new FileWriter(filePath,true);
            fileWriter.write("heool");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.2.2、BufferedWriter
public class BufferedWriterTest {
    public static void main(String[] args) {
        String filePath = "G:\\hello.txt";
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
            bufferedWriter.write("hah");
            bufferedWriter.newLine();// 换行符
            bufferedWriter.write(65);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

4.2.3、OutputStreamWriter

OutputStreamWriter是Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)。当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,建议将字节流转换成字符流。

public class transformationTest02 {
    public static void main(String[] args) {
        transformationIo();
    }

    /**
     * @description: 把 FileInputStream(字节流) 转换为 OutputStreamWriter(字符流)
     * @return: void
     */
    public static void transformationIo(){
        String filePath = "G:\\test.txt";
        OutputStreamWriter or = null;
        BufferedWriter br = null;
        try {
            or = new OutputStreamWriter(new FileOutputStream(filePath),"gbk");
            br = new BufferedWriter(or);
            try {
                br.write("hello,你好啊!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.3、PrintStream

public class PrintStreamTest {
    public static void main(String[] args) {
        PrintStream out = System.out;
        out.print("hello world!");
        try {
            out.write("hello world!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.close();

        // 可以修改打印流输出的位置/设备
        try {
            System.setOut(new PrintStream("G:\\test.txt"));
            System.out.println("啊这....");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

5、节点流和处理流

5.1、定义

  1. 节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter
  2. 处理流(也叫包装流)是”连接“在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedReader、BufferedWriter

5.2、区别和联系

  1. 节点流是底层流/低级流,直接跟数据源相接。
  2. 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。
  3. 处理流(也叫节点流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连。

5.3、处理流的作用

  1. 性能的提高:主要以增加缓冲的方式来提高输入输出的效率。
  2. 操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便。

5.4、对象处理流 使用细节

  1. 读写顺序要一致。
  2. 要求实现序列化或反序列化对象,需要实现Serializable。
  3. 序列化的类中建议添加SeriaIVersionUID,为了提高版本的兼容性。
  4. 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员。
  5. 序列化对象时,要求里面属性的类型也需要实现序列化接口。
  6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化。

5.5、标准输入/输出流

  1. System.in 标准输入,属InputStream类型
  2. System.out 标准输出,属PrintStream类型

6、部分例子

6.1、文件拷贝(字节流)

public class FileCopyEg {
    public static void main(String[] args) {
        copyFile();
    }

    /**
     * @description: 文件拷贝
     * @return: void 
     */
    public static void copyFile(){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        String srcFilePath = "C:\\Users\\hw\\Desktop\\国家地图.jpg";
        String destFilePath = "G:\\map.jpg";
        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath,true);
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1){
                fileOutputStream.write(buf,0,readLen);
            }
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

6.2、文本文件拷贝(处理流)

public class FileCopyEg02 {
    public static void main(String[] args) {
        copyFile(); // 不能读取二进制文件,因为是按照字符操作的。
    }

    public static void copyFile(){
        String srcFilePath = "C:\\Users\\hw\\Desktop\\hello.txt";
        String destFilePath = "G:\\test.txt";
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        String res;
        try {
            bufferedReader = new BufferedReader(new FileReader(srcFilePath));
            bufferedWriter = new BufferedWriter(new FileWriter(destFilePath, true));
            while ((res = bufferedReader.readLine()) != null){
                bufferedWriter.write(res);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

6.3、文件拷贝(处理流)

public class FileCopyEg03 {
    public static void main(String[] args) {
        copyFile(); // 读取二进制文件,也可以操作文本文件,因为字节是根本,但是效率低。
    }

    public static void copyFile(){
        String srcFilePath = "C:\\Users\\hw\\Desktop\\国家地图.jpg";
        String destFilePath = "G:\\map.jpg";
        BufferedInputStream bufInStream = null;
        BufferedOutputStream bufOutStream = null;
        try {
            bufInStream = new BufferedInputStream(new FileInputStream(srcFilePath));
            bufOutStream = new BufferedOutputStream(new FileOutputStream(destFilePath));
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = bufInStream.read(buf)) != -1){
                bufOutStream.write(buf,0,readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufInStream != null) {
                try {
                    bufInStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufOutStream != null) {
                try {
                    bufOutStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

7、Properties类(配置文件)

7.1、常见方法

  1. load:加载配置文件的键值对到properties对象。
  2. list:将数据显示到指定设备。
  3. getProperty(key):根据键获取值。
  4. setProperty(key,value):设置键值对到Properties对象。
  5. store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码。

7.2、代码

public class propertiesTest {
    public static void main(String[] args) throws IOException {
        // getMsg();
        // getMsgProperties();
        setMsgProperties();
    }

    /**
     * @description: 传统方法获取数据
     * @return: void
     */
    public static void getMsg(){
        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader("F:\\Spring-boot-Projects\\javaProjectTest\\src\\iostream\\properties_\\mysql.properties"));
            while ((line = br.readLine()) != null){
                String[] split = line.split("=");
                System.out.println(split[0] + " 值是:" + split[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * @description: Properties获取数据
     * properties 专门用于读写配置文件
     * 格式:键=值
     * 要求:键值对不需要空格 + 值不需要引号
     * @return: void
     */
    public static void getMsgProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(new FileReader("F:\\Spring-boot-Projects\\javaProjectTest\\src\\iostream\\properties_\\mysql.properties"));
        properties.list(System.out);

        String user = properties.getProperty("user");
        System.out.println(user);
    }

    /**
     * @description: 添加配置信息到配置文件
     * @return: void
     */
    public static void setMsgProperties() throws IOException {
        Properties properties = new Properties();
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");
        properties.setProperty("pwd","123456789");
        properties.store(new FileWriter("src\\iostream\\properties_\\mysql02.properties"),null);// comments:添加注释的
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值