java(equal方法重构+常见异常+异常处理+面向对象总结+集合数组介绍和遍历+Collections工具类+FILE+线程+字符串转化)

equal方法重构

package com.company;

public class Main {

    public static void main(String[] args) {
        oder o1 =new oder(1001,"aa");
        oder o2 =new oder(1001,"aa");
        System.out.println(o1 == o2);

        System.out.println(o1.equals(o2));

    }


}

class oder{
    private int orderid;
    private String ordername;

    public oder(int orderid, String ordername) {
        this.orderid = orderid;
        this.ordername = ordername;
    }

    public int getOrderid() {
        return orderid;
    }

    public void setOrderid(int orderid) {
        this.orderid = orderid;
    }

    public String getOrdername() {
        return ordername;
    }

    public void setOrdername(String ordername) {
        this.ordername = ordername;
    }

    //比较两个order对象的属性是否完全相等
    public boolean equals(Object obj){
        if(this ==obj){
            return true;
        }else if (obj instanceof oder){
            oder o1 = (oder)obj;
            return this.orderid ==o1.orderid &&this.ordername.equals(o1.ordername);

        }else {
            return false;
        }
    }
}


结果

false
true

建议右键Generate然后再选中equl一键生成equal代码;就不用自己写了;
在这里插入图片描述

常见异常


package testrapper;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

import java.util.Scanner;

/**
 * @Auther: ljm
 * @Date: 2021/04/02/10:53
 * @Description:
 * java.lang.Throwable
 * -----Error:错误,程序中不进行处理
 * ----Exception:异常,要求在编写程序时,就要考虑到对这些异常的处理
 * ----编译时异常:在编译期间会出现的异常(执行javac.exe命令时,出现异常)
 * ----运行时异常:在运行期间出现的异常(执行java.exe命令时,出现异常)

 * 当执行一个程序时,如果出现异常,那么异常之后的代码就不再执行!
 */

public class testexception {


    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/2
    * @Description: 数组下标越界
     * ArrayIndexOutOfBoundsException: 10
    */
    @Test
    public void test1(){
        int[] i =new int[10];
        System.out.println(i[10]);
    }


    /**
     * @Param: []
     * @return: void
     * @Author: ljm
     * @Date: 2021/4/2
     * @Description:算数异常
     * java.lang.ArithmeticException: / by zero
     */
    @Test
    public void test2(){
        int i=10;
        System.out.println(i/0);
    }
    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/2
    * @Description:类型转换异常
     * java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String
    */
    @Test
    public void test3(){

        Object OBJ = new Date();
        String str = (String) OBJ;


    }
    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/2
    * @Description:空指针异常
     * java.lang.NullPointerException
     *
     * /
     * Bank bank = new Bank();
     * *Customer[]customers = new Customer[5];
     * *customers[e]= new customer();
     * *System.out.println(customers[0].getFirstName());可能出现空指针异常
     * *customers[0].setAccount(new Account(200));
     * *customers[0].getAccount().withdraw(100);可能出现空指针异常
     * */
    @Test
    public void test4(){

        person p = new person();
        p=null;
        System.out.println(p.toString());


    }
    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/2
    * @Description: 编译时异常
     *
    */
    @Test
    public void test6() throws Exception{

        FileInputStream fis = new FileInputStream(new File("hellow.txt"));
        boolean b = false;


    }





}

class person{

}

异常处理

package testrapper;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

/**
 * @Auther: ljm
 * @Date: 2021/04/02/12:00
 * @Description:
 * 二、如何处理Exception的异常
 * Java提供的是异常处理的抓抛模型
 * 1."抛",当我们执行代码时,一旦出现异常,就会在异常的代码处生成一个对应的异常类型的对象,并将此对象抛出.
 * >一旦抛出此异常类的对象,那么程序就终止执行
 * >此异常类的对象抛给方法的调用者
 * 2.“抓",抓住上一步抛出来的异常类的对象。如何拭?即为异常处理的方式java 提供了两种方式用来处理一个异常类的对象
 * 处理的方式一:
 * try{
 * //可能出现异常的代码
 * }catch(Exception1 el){
 * //处理的方式1
 * }catch(Exception2 e2){
 * 1/处理的方式2
 * }finally{
 * //-建要执行的代码
 * }
 *
 *注:1.try内庄明的变量,类似于局部变量,出了tryt{}语句,就不能被调用
 * 2.final1y是可选的.
 * 3.catch语句内部是对异常对象的处理:
 * getMessage();printstackTrace();
 * 4,可以有多个catch语句,try中抛出的异常类对象从上往下去匹配catch中的异常类的类型,一旦满足就执行catch中的代码。执行完,就跳出其后的多条catch语句
 * 5,如果异常处理了,那么其后的代码继续执行。
 * 6·若catch中多个异常类型是"并列"关系,孰上孰下都可以若catch中多个异常类型是“包含"关系,须将子类放在父类的上面,进行处理。否则报错!
 *7..finally中存放的是一定会被执行的代码,不管try中、catch中是否仍有异常未被处理,以及是否有return语句
 * 8.tryEcatch是可以嵌套的。
 *三、对于运行时异常来说,可以不显式的进行处理。
 * 对于编译时异常来说,必须要显式的进行处理。
 *
 *
 * 快速调用
 * try catch
 *
 * 选中代码行
 *
 * 按住ctrl + alt + t
 * https://blog.csdn.net/jianeng_Love_IT/article/details/83176872

 */

public class testexception1 {

    /**
     * @Param:
     * @return:
     * @Author: ljm
     * @Date: 2021/4/2
     * @Description: 数组下标越界
     * ArrayIndexOutOfBoundsException: 10
     */
    @Test
    public void test1(){
        try{
        int[] i =new int[10];
        System.out.println(i[10]);
        }catch (Exception e){
            //System.out.println("出现异常");
            //e.printStackTrace();
            System.out.println(e.getMessage());

        }

    }


    /**
     * @Param:
     * @return:
     * @Author: ljm
     * @Date: 2021/4/2
     * @Description:类型转换异常
     * java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String
     */
    @Test
    public void test3(){

        try {
            Object OBJ = new Date();
            String str = (String) OBJ;
        } catch (Exception e) {
            e.printStackTrace();
        }


    }





}

package testrapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @Auther: ljm
 * @Date: 2021/04/02/17:32
 * @Description:
 * 异常处理的方式二,在方法的声明处,显式的抛出该异常对象的类型
 * 格式:public static void method2() throws FileNotFoundException
 *
 * 当在此方法内部出现异常的时候,会抛出一个异常类的对象,抛给方法的调用者。
 * 异常的对象可以逐层向上抛,直至main中。当然在向上抛的过程中,可以再通过try-catEh-finally进行处理。
 * java的异常处理,抓抛模型
1,抓:异常的处理,有两种方式(①try-catch-finally② throws +异常的类型)
2,抛,一旦执行过程中,出现异常,会抛出一个异常类的对象。(自动的vs手动的抛出(throw+异常类的对象))
手动的抛出
抛出的异常类型,若是RuntimeException,可以不显式的处理若是一个Exception,必须要显式的处理。

 */

public class testexception2 {
    public static void main(String[] args) {
        try {
            method2();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
    public static void method2() throws FileNotFoundException {
        method1();
    }
    public static void method1() throws FileNotFoundException {
        FileInputStream file = new FileInputStream(new File("HELLOW.txt"));
    }

}

package testrapper;

/**
 * @Auther: ljm
 * @Date: 2021/04/02/18:03
 * @Description:
 * 如何自定义一个异常类
 * 1,自定义的异常类继承现有的异常类
 * 2,提供一个序列号,提供几个重载的构造器
 */
public class myexception extends  RuntimeException{
    static final long serialVersionUID = -7034897190745766939L;

    public  myexception(){

    }

    public myexception(String message) {
        super(message);
    }

    public myexception(String message, Throwable cause) {
        super(message, cause);
    }

    public myexception(Throwable cause) {
        super(cause);
    }

    public myexception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

面向对象总结

面向对象的三条主线:
1.类及类的成分
2.面向对象的三大特性
3其他的关键字:this super import package abstract static final interface等

1.java程序是关注于类的设计。
类从代码的角度:并列关系!从执行、设计的角度:关联关系、继承关系、聚合关系

class A{class B
{
A a =new A();
}

2.类的成分:属性方法构造器代码块内部类
2.1属性:
①变量的分类:成员变量(属性Field)vs局部变量(方法的形参、方法内部、代码块内部)
基本数据类型(8种,不同的数据类型对应不同的默认初始化值)vs引用数据类型(数组、类、接口默认初始化值为null)
②属性的声明格式:修饰符 数据类型 变最名=初始化值;/java是强数据类型的语言
③对属性的赋值的操作:1.默认初始化2.显式的初始化3.代码块的初始化4.构造器的初始化;5.调用方法、属性进行赋值
2.2方法
①格式:修饰符(其它的关键字:static/final/abstract)返回值类型方法名(形参列表){//方法体}
②方法的重载(overload)vs方法的重写(override overwrite)
③方法的参数传递机制:值传递(难点)
2.3构造器@构造器的作用:1.创建类的对象2.初始化对象的成员变量
②构造器也是可以重载的。
2.4代码块主要作用:用来初始化类的成员变量
分类:静态的代码块vs非静态的代码块
2.5内部类分类:成员内部类(static的成员vs 非static的成员)vs局部内部类(方法内部声明的类)
②掌握: ①如何创建成员内部类的对象(如:创建Bird类和Dog类的对象)
②如何区分调用外部类、内部类的变量(尤其是变是重名时)
③局部内部类的使用(见TestinnerClass1.java)

3.类的初始化(创建类的对象)

3.1如何创建类的对象。如:Person p = new Person():Date d=new Date():
3.2内存解析:
①栈:局部变量、对象的引用名、数组的引用名
堆:new出来的"东西"
方法区:(字符串常量池)
静态域:存放类中静态的变量
②如何理解创建的对象在内存中加载的过程(理解)
3.3子类对象实例化的全过程:SubClass sc = new SubClass();

4面向对象的三大特性:
4.1封装性:
①通过私有化类的成员变量,通过公共的getter和setter方法来调用和修改
②还可以对类的其他结构进行"封装"
③权限修饰符:public protected缺省private
4.2继承性:通过让一个类A继承另一个类B,就可以获取类B中的结构(主要的:属性、方法、构造器).子类:类A父类:类B java中的类的继承性:单继承的
4.3多态性:
①体现:方法的重载与重写;子类对象的多态性Person p=new Student();
②子类对象多态性的使用:虚拟方法调用。
③向上转型向下转型Student s =(Student)p;//建议在向下转型之前:if(p instanceof Student)避免出现ClassCastException的异常

5其它关键字:
5.1 this:修饰属性、方法、构造器,表示:当前对象或当前正在创建的对象5.2 super:修饰属性、方法、构造器,显式的调用父类的相应的结构,尤其是子父类有重名的方法、属性
5.3 static:修饰属性、方法、代码块、内部类,随着类的加载而加载!
5.4 final:修饰类、属性、方法,表示"最终的"
5.5 abstract:修饰类、方法
5.6 interface:表示是一个接口,(接口是与类并列的一个结构).类与接口之间同时"implements"发生关系。
5.7 package import…
abstract不能修饰属性、构造器、不能与final static private共用.

6、bank项目:加深理解

集合数组遍历

package testrapper;

import org.junit.Test;

import java.util.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/03/9:44
 * @Description:
 *1,存储对象可以考虑:①数组②集合
 *2,数组存储对象的特点:student[]stu = new student[20];stu[0]= new student();.....
 * >弊端:①一旦创建,其长度不可变。②真实的数组存放的对象的个数是不可知。
 *
 */
public class testinteraction {
    //集合(遍历方法)
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.addAll(Arrays.asList(1,2,3,4));
//        Collections.addAll(coll,12,13,14);
        //iterator方法
        Iterator i = coll.iterator();
        while (i.hasNext()){
            System.out.println(i.next());
        }
        System.out.println("*********");
        //增强for循环
        for(Object i1:coll){
            System.out.println(i1);
        }
    }


    //增强for循环(遍历数组)
    @Test
    public void  testfor1(){
        String[]  str = new String[]{"qq","a","ss"};
        //增强for循环(数组)
        for(Object S:str){
            System.out.println(S);
        }
        //普通for循环
        for(int i=0;i<str.length;i++){
            System.out.println(str[i]);
        }

    }

    //面试题
    @Test
    public void test2(){
        String[]  str = new String[]{"aaa","ccc","fff"};
        for (int i=0 ; i<str.length;i++){
            str[i] = i+"";
        }
        for (int j =0 ;j<str.length;j++){
            System.out.println(str[j]);
        }




    }

    @Test
    public void test22(){
        String[]  str = new String[]{"aaa","ccc","fff"};

        //增强for循环
        System.out.println("增强for循环查看变化");
        for(Object s:str){
            s = "MM";//此处的s是新定义的局部变量,其值的修改不会对str本身造成影响。
        }

        for (int j =0 ;j<str.length;j++){
            System.out.println(str[j]);
        }




    }



}

集合介绍

list

package testrapper;

import org.junit.Test;

import java.sql.Array;
import java.util.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/03/9:44
 * @Description:
 *1,存储对象可以考虑:①数组②集合
 *2,数组存储对象的特点:student[]stu = new student[20];stu[0]= new student();.....
 * >弊端:①一旦创建,其长度不可变。②真实的数组存放的对象的个数是不可知。
 *3.集合
 * Collection接口
 * ------List接口:存储有序的,可以重复的元素
 * l------ArrayList(主要的实现类)LinkedList(对于频繁的插入、删除操作建议这个).Vector(古老的实现类、线程安全的)
 * 1----Set接口,存储无序的,不可重复的元素
 * I---HashSet,LinkedHashSet,TreeSet Map接口,存储"键-值”对的教据
 * 1-----HashMap.LinkedHashMap.TreeMap.Hashtable(子类:Properties)
 */
public class testlist {
    //ArrayList,list主要实现类,动态数组
    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description:
     * List中相对于Collection,新增加的方法void add(int index,object ele):在指定的素引位置index添加元素ele
     * boolean addAll(int index,Collection eles)
     * object get(int index):获取指定索引的元素
     * object remove(int index):删除指定索引位置的元素
     * object set(int index,object ele)::设置指定索引位置的元素为ele
     * int indexof(object obj):返回obj在集合中首次出现的位置。没有的话,返回-1
     * int lastIndexof(object obj),返回obj在集合中最后一次出现的位置,没有的话,返回-1
     * List subList(int fromIndex,int toIndex):返回从fromIndex到toIndex结束的一个子list,不含toIndex的元素,左闭右开
     *
     * List常用的方法,增(add(object obj))删(remove)改(set(int index,object obj))
     * 查(get(int index))插(add(int index,object elel)长度(size())
    */
    @Test
    public void testlist1(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add(new String("AA"));
        list.add(new String("gg"));
        System.out.println(list);
        list.add(0,555);
        System.out.println(list);
        //获取指定位置的元素
        Object OBJ=list.get(1);
        System.out.println(OBJ);
        list.remove(0);
        System.out.println(list.get(0));
        list.set(0,111);
        //第一个元素
        System.out.println(list.get(0));
        //长度
        System.out.println(list.size());


        //首次出现的位置
        System.out.println(list.indexOf(555));

        System.out.println(" Iterator 遍历");

        Iterator I = list.iterator();
        while(I.hasNext()){
            System.out.println(I.next());
        }

        System.out.println("for增强遍历");

        for (Object l :list){

            System.out.println(l);
        }
        System.out.println("一般for遍历");
        //一般for循环遍历
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }




    }








}

set

package testrapper;

import org.junit.Test;

import java.util.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/03/16:26
 * @Description:
 * Collection接口:l------List接口:
 * --ArrayList(主要的实现类)、
 * -LinkedList(对于频繁的插入、删除操作)、
 * ------Vector(古老的实现类、线程安全的,但效率要低于ArrayList)
 * 1------Set接口:存储无序的,不可重复的元素,Set中常用的方法都是Collecti.on下定义的。
 * -----ashSet(主要实现类)
 * ------LinkedHashSet
 * ------TreeSet
 */
public class testset {

    /**
     * @Param: []
     * @return: void
     * @Author: ljm
     * @Date: 2021/4/3
     * @Description:
     * Set:存储的元素是无序的,不可重复的!
     * 1.无序性:无序性!=随机性,真正的无序性,指的是元素在底层存储的位置是无序的。
     * 2.不可重复性;当向set中添加相同元素时,后面不能添加进去;
     * 说明,要求添加进Set中的元素所在的类,一定要重写equals()和hashCode()方法。
     * 进而表示可重复性
     *
     * Set中的元素时如何存储的呢?使用了哈希算法。
     * 当向Set中添加对象时,首先调用此对象所在类的hashCode()方法,计算此对象的哈希值,此哈希值决定了此对象在Set中的存储位置。
     * 若此位置之前没有对象存储,则这个对象直接存储到此位置。
     * 若此位置已有对象存储,再通过equals()比较这两个对象是否相同。
     * 如果相同,后一个对象就不能再添加进来。
     * 万一返回false呢,(不建议如此)
     * >要求:hashCode()方法要与equals()方法一致。
     */
    @Test
    public void testhashset(){


        HashSet set = new HashSet();
        set.add(null);
        set.add(123);
        set.add("aa");
        set.add("aaa");
        set.add("aaa1a");
        persin p = new persin(22,"l");
        persin p1 = new persin(22,"l");
        set.add(p);
        set.add(p1);
        System.out.println(set.size());
        System.out.println(set);



    }

    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date:
    * @Description:
     *  LinkedHashSet:
     *  * 使用链表维护了一个添加进集合中的顺序。导致当我们遍历LinkedHashSet集合元素时,是按照添加进去的顺序遍历的!
     *  LinkedHashSet插入性能略低于HashSet,但在迭代访问Set里的全部元素时有很好的性能。
    */

    @Test
    public void testlinkhashset(){
        HashSet set = new LinkedHashSet();
        set.add(null);
        set.add(123);
        set.add("aa");
        set.add("aaa");
        set.add("aaa1a");

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }


    }

    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description:
     * TreeSet:
     * 1,向TreeSet中添加的元素必须是同一个类的。
     * 2,可以按照添加进集合中的元素的指定的顺序遍历。
     * 像String,包装类等默认按照从小到大的顺序遍历
     * 3,当向TreeSet中添加自定义类的对象时,有两种排序方法:@自然排序定制排序
     * 4,自然排序:要求自定义类实现java.lang.Comparable接口并重写其compareTo(object obj)
     * 在此方法中,指明按照自定义类的哪个属性进行排序。
     * 5.向Treeset中添加元素时,首先按照compareTo()进行比较,一旦返回e,
     * 虽然仅是两个对象的此属性值相同,但是程序会认为这两个对象是相同的,进而后一个对象就不能添加进来。
     * >compareTo()与hashCode()以及equals()三者保持一致!
     *
    */
    @Test
    public void testTreeset(){
        Set set = new TreeSet();

//        set.add("aa");
//        set.add("b");
//        set.add("aaa");
//        set.add("aaa1a");

        //当Person类没有实现Comparable接口时,当向TreeSet中添加Person对象时,报ClassCastExceptior

        set.add(new persin(20,"DD"));
        set.add(new persin(21,"ff"));
        set.add(new persin(30,"gg"));
        set.add(new persin(40,"bb"));
        set.add(new persin(40,"bb1"));


        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }


    }
    
    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description: TreeSet的定制排序
     * compare()与hashCode()以及equals()三者保持一致!
     *
     *
    */

    @Test
    public void testTreeset2(){


        //见下面的步骤
        1.创建一个实现了Comparator接口的类对象
        //向Treeset中添加customer类的对象,在此compare()方法中,指明是按照customer
//的哪个尾性排序的
        Comparator com = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof customer && o2 instanceof customer){
                    customer c1 = (customer)o1;
                    customer c2 = (customer)o2;
                    int i = c1.getId().compareTo(c2.getId());
                    if (i == 0) {
                        return c1.getName().compareTo(c2.getName());
                    }else {
                        return i;
                    }

                }
                return 0;
            }
        };

        //2.将此对象作为形参传递给TreeSet的构造器总
        TreeSet set =new TreeSet(com);
        //3.向TreeSet中添加Comparator接口中的compare方法中涉及的类的对象
        set.add(new customer(11,"11"));
        set.add(new customer(22,"221"));
        set.add(new customer(31,"31"));
        set.add(new customer(44,"44"));
        set.add(new customer(55,"15"));
        set.add(new customer(55,"151"));

        for (Object l:set){
            System.out.println(l);
        }



    }




}

class persin implements  Comparable{
    private int age;
    private String NAME;

    public persin(int age, String NAME) {
        this.age = age;
        this.NAME = NAME;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getNAME() {
        return NAME;
    }

    public void setNAME(String NAME) {
        this.NAME = NAME;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        persin persin = (persin) o;
        return age == persin.age && Objects.equals(NAME, persin.NAME);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, NAME);
    }

    //当向TreeSet中添加Person类的对象时,依据此方法,确定按照哪个属性排列。
    @Override
    public int compareTo(Object o) {
        if(o instanceof persin){
            persin p  = (persin) o;
            //return this.NAME.compareTo(p.NAME);
//            return this.age-p.age;
            int i =(this.age-p.age);
            if (i==0){
                return this.NAME.compareTo(p.NAME);

            }else {
                return i;
            }
        }
        return 0;
    }
}

map

package testrapper;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/03/21:13
 * @Description:
 * Collection接口
 * Map接口
 * HashMap:Map的主要实现类
 * LinkedHashMap:使用链表维护添加进Map中的顺序。故遍历Map时,是按添加的顺序遍历的.
 * TreeMap::按照添加进Map中的元素的key的指定属性进行排序,要求;key必须是同一个类的对象!
 * 针对key;自然排序vs定制排序
 * Hashtable:古老的实现类,线程安全,不建议使用。
 * roperties:常用来处理属性文件。键和值都为string类型的
 */
public class testmap {
    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description:
     * object put(object key,object value):向Map中添加一个元素
     * object remove(object key):按照指定的key删除此key-value
     * void putAll(Map t)
     * void clear():清空
     * object get(object key):获取指定key的value值,若无key,返回null
     * boolean containsKey(object key)
     * boolean containsValue(Object value)
     * int size():返回集合长度
     * boolean isEmpty()
     * boolean equals(object obj)
     *
     * HashMap:key是用Set来存放的,不可重复.value是用Collection来存放的,可重复
     * 一个key-value对,是一个Entry.所有的Entry是用Set存放的,也是不可重复的。
     * 2,向HashMap中添加元素时,会调用key所在类的equals()方法,判断两个key是否相同.若相同则只能添加进后添加的那个元素。
    */
    @Test
    public void test1(){
        Map map = new HashMap();
        map.put("AA",111);
        map.put("BB",112);
        map.put(null,null);
        System.out.println(map.size());


     }
     /**
     * @Param:
     * @return:
     * @Author: ljm
     * @Date: 2021/4/3
     * @Description:
      * 如何遍历Map
      * Set keySet
      * Collection values()
      * Set entrySet()
     */
     @Test
     public void test2(){
         Map map = new HashMap();
         map.put("AA",111);
         map.put("BB",112);
         map.put(null,null);


         //1.遍历key集
         Set set = map.keySet();
         for(Object obj:set){
             System.out.println(obj);
         }

         //2、遍历value集
         Collection values = map.values();
         Iterator i = values.iterator();
         while (i.hasNext()){
             System.out.println(i.next());
         }

         //3如何遍历key-values对
         //方式1
         Set set1= map.keySet();
         for (Object OBJ:set1){
             System.out.println(OBJ+"--》"+map.get(OBJ));
         }
         //方式2
         Set SET2 = map.entrySet();
         for (Object obj:SET2){
             Map.Entry entry = (Map.Entry) obj;
             //System.out.println(entry.getKey()+"--->"+entry.getValue());
             System.out.println(entry);
         }


     }


     @Test
    public void test3(){
         Map map = new LinkedHashMap();
         map.put("AA",111);
         map.put("BB",112);
         map.put(null,null);
         //方式2
         Set SET2 = map.entrySet();
         for (Object obj:SET2){
             Map.Entry entry = (Map.Entry) obj;
             //System.out.println(entry.getKey()+"--->"+entry.getValue());
             System.out.println(entry);
         }
     }
     //自然排序
     @Test
    public  void test4(){
         Map map = new TreeMap();
         map.put(new persin(11,"a"),99);
         map.put(new persin(12,"a"),93);
         map.put(new persin(22,"a"),92);
         map.put(new persin(23,"a"),92);


         Set set = map.entrySet();
         for (Object obj:set){
             Map.Entry entry  =(Map.Entry) obj;
             System.out.println(entry);

         }


     }
    //定制排序
    @Test
    public  void test5(){
         Comparator com = new Comparator() {
             @Override
             public int compare(Object o1, Object o2) {
                 if(o1 instanceof persin &&o2 instanceof persin){
                     persin p1 = (persin) o1;
                     persin p2 = (persin) o2;
                     int i = (p1.getAge()-p2.getAge());
                     if(i==0){
                         return p1.getNAME().compareTo(p2.getNAME());
                     }else {
                         return i;
                     }

                 }
                 return 0;
             }
         };
        Map map = new TreeMap(com);
        map.put(new persin(11,"a"),99);
        map.put(new persin(12,"a"),93);
        map.put(new persin(22,"a"),92);


        Set set = map.entrySet();
        for (Object obj:set){
            Map.Entry entry  =(Map.Entry) obj;
            System.out.println(entry);

        }


    }
    //使用Properties处理属性文件
    @Test
    public  void test6() throws IOException {
         Properties pros = new Properties();
         pros.load(new FileInputStream(new File("jdbc.properties")));
         String user = pros.getProperty("user");
        System.out.println(user);

    }





}

Collections工具类

package testrapper;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Auther: ljm
 * @Date: 2021/04/03/22:16
 * @Description:
 * 操作Collection以及Map的工具类:Collections
 * 面试题:区分Collection与Collections
 */
public class testcollestions {
    /**
    * @Param: 
    * @return: 
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description: object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
     * object max(collection,Comparator):根据Comparator指定的顺序,返回给定集合中的
     * Object min(Collection)
     * Object min(Collection,Comparator)
     * int frequency(Collection,object):返回指定集合中指定元素的出现次数
     * void copy(List dest,List src):将src中的内容复制到dest中
     * boolean replaceAll(List list,object oldval,Object newVal):使用新值替换L
    */
    @ Test
    public void  test2(){
        List list = new ArrayList();
            list.add(123);
            list.add(456);
            list.add(12);
            list.add(78);
            list.add(78);
            Object OBJ= Collections.max(list);
        System.out.println(OBJ);
        int count = Collections.frequency(list,78);
        System.out.println(count);

        //实现List的复制
        //List list1 = new ArrayList();//错误的实现方式
        List list1 = Arrays.asList(new Object[list.size()]);
        Collections.copy(list1,list);
        System.out.println(list1);
        //通过如下的方法保证list的线程安全性。
        List LIST2= Collections.synchronizedList(list);
        System.out.println(LIST2);

    }
    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/3
    * @Description:
     * reverse(List):反转List中元素的顺序
     * shuffle(List):对List集合元素进行随机排序
     * sort(List):根据元素的自然顺序对指定List集合元素按升序排序
     * sort(List,Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序
     * swap(List,int,int):将指定1ist集合中的1处元素和j处元素进行交换
    */
    @Test
    public void test1(){
        List list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add(12);
        list.add(78);
        System.out.println(list);
        Collections.reverse(list);
        System.out.println(list);

        Collections.shuffle(list);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);

        Collections.swap(list,2,1);
        System.out.println(list);


    }
}

FILE

File类

package testfile;

import org.junit.Test;

import java.io.File;

/**
 * @Auther: ljm
 * @Date: 2021/04/04/19:43
 * @Description:
 * java.io.File类
 * 1·凡是与输入、输出相关的类、接口等都定义在java.io包下
 * 2.File是一个类,可以有构造器创建其对象。此对象对应着一个文件(.txt.avi.doc.ppt.mp3.jpg)或者文件夹
 * 3.File类对象是与平台无关的。
 * 4.File中的方法,仅涉及到如何创建、删除、重命名等等,只要涉及文件内容的,File是无能为力的,必须由io流来完成.
 * 5.File类的对象常作为io流的具体类的构造器的形参。
 */
public class testfile {
    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/4
    * @Description:
     *
     * getName ()
     * getPath()
     * getAbsoluteFile()
     * getAbsolutePath()
     * getParent()
     * renameTo(File newName)
     *
     *
     * exists()
     * canWrite()
     * canRead()
     * isFile()
     * isDirectory()
     * lastModified()
     * length()
     *
     *
     * createNewFile()
     * delete()
     * mkDir():创建一个文件目录。只有在上层文件目录存在的情况下,才能返回true
     * mkDirs ():创建一个文件目录。若上层文件目录不存在,一并创建
     * list()
     * listFiles()
    */
    @Test
    public void test1(){
        File file1 = new File("hellow.txt");
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getName());
        System.out.println(file1.getPath());
        System.out.println(file1.getParent());
        System.out.println(file1.getAbsoluteFile());


//renameTo(File newName):重命名
//file1.renameTo(file2):file1重命名为file2.要求:file1文件一定存在,file2-定不存在




    }
}

节点流(文件流)

package testfile;

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Auther: ljm
 * @Date: 2021/04/04/20:35
 * @Description:
 * 1.流的分类
 * 按照数据流向的不同:输入流输出流按照处理数据的单位的不同:字节流字符流(处理的文本文件)
 * 按照角色的不同,节点流(直接作用于文件的)处理流
 * 2.IO的体系
 * 抽象基类
 * Inputstream
 * OutputStream
 * Reader
 * Writer
 * 节点流(文件流)
 * Filelnputstream
 * FileOytputStream
 * FileReader
 * FileWriter
 */
public class testfileinputoutput {
    //从硬盘存在的一个文件中,读取其内容到程序中。使用FileInputStream
//要读取的文件一定要存在。否则抛FileNotFoundException
    @Test
    public void testinputstream1() throws IOException {
        //1,创建一个File类的对象。
        File file =new File("F:\\java code\\src\\testfile\\hellow.txt");
        //2.创建一个FileInputStream类的对象
        FileInputStream fis = new FileInputStream(file);
        //3、调用FileInputStream方法实现读取
        //read():读取文件的一个字节。
//        int b = fis.read();
//        while (b!=-1){
//            System.out.print((char)b);
//            b=fis.read();
//
//        }
        int b;
        while ((b = fis.read())!=-1){
            System.out.println((char)b);
        }

        //4.关闭相应的流
        fis.close();

    }
    //使用try-catch的方式处理如下的异常更合理!:保证流的关闭操作一定可以执行
    @Test
    public void testinputstream2(){
        FileInputStream fis = null;

        try {
            //1,创建一个File类的对象。
            File file =new File("F:\\java code\\src\\testfile\\hellow.txt");
            //2.创建一个FileInputStream类的对象
            fis = new FileInputStream(file);
            //3、调用FileInputStream方法实现读取
            //read():读取文件的一个字节。
//        int b = fis.read();
//        while (b!=-1){
//            System.out.print((char)b);
//            b=fis.read();
//
//        }
            int b;
            while ((b = fis.read())!=-1){
                System.out.println((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.关闭相应的流
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }

    @Test
    public void  test3(){
        FileInputStream fis = null;
        try {
            File file =new File("F:\\java code\\src\\testfile\\hellow.txt");
            fis = new FileInputStream(file);
            byte[] b = new byte[20];//读取到数据要写入到数组
            int len;//记录每次读入到byte的字节的长度
            while ((len=fis.read(b))!=-1){
                for (int i= 0;i<len;i++){
                    System.out.print((char) b[i]);
                }
//                String str = new String(b,0,len);
//                System.out.println(str);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    //FileOutputStream
    @Test
    public void testoutputstream(){
        //1、创建一个file对象,表明要写入的文件weizhi
        //输出的物理文件可以不存在,当执行过程中如果不存在,自动创建,若存在,将原有的文件覆盖。
        File file =new File("hellow2.txt");
        //2、创建一个FileOutputStream对象,将file对象作为形参传递给FileOutputStream的构造器中
        FileOutputStream fos =null;
        try {
            fos = new FileOutputStream(file);
            //3、写入操作
            fos.write(new String("i love you").getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //4、关闭输出流
            if(fos!= null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    //从硬盘读取一个文件,并写入到另一个位置。(相当于文件的复制)
    @Test
    public void testinputoutputstream(){
        //1,提供读入、写出的文件
        File file1 = new File("F:\\java code\\src\\testfile\\hellow.txt");
        File file2 = new File("hellow3.txt");
        FileInputStream fis =null;
        FileOutputStream  fos =null;
        //2、提供相应的流
        try {
            fis = new FileInputStream(file1);
            fos = new FileOutputStream(file2);
            //3、实现文件的复制
            byte[] b = new byte[20];
            int len;
            while ((len = fis.read(b))!=-1){
                //fos.write(b);错误的写法,另一个错误写法fos.write(b,0,b.length);
                fos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }

    //实现文件复制的方法
    public static void copyfile(String src , String dest){
        //1,提供读入、写出的文件
        File file1 = new File(src);
        File file2 = new File(dest);
        FileInputStream fis =null;
        FileOutputStream  fos =null;
        //2、提供相应的流
        try {
            fis = new FileInputStream(file1);
            fos = new FileOutputStream(file2);
            //3、实现文件的复制
            byte[] b = new byte[20];
            int len;
            while ((len = fis.read(b))!=-1){
                //fos.write(b);错误的写法,另一个错误写法fos.write(b,0,b.length);
                fos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
    @Test
    public void testcopyfile(){
        String src = "hellow3.txt";
        String dest = "hellow4.txt";
        copyfile(src,dest);

    }



}

package testfile;

import org.junit.Test;

import java.io.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/04/22:19
 * @Description:
 */
public class testfilereaderwrite {
    @Test
    public void testfilereader(){
        FileReader fr = null;
        try {
            File file = new File("hellow4.txt");
            fr = new FileReader(file);
            char[] c = new char[24];
            int len;
            while (((len=fr.read(c))!=-1)){
                String str = new String(c,0,len);
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr!=null){
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        }

    }

    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/5
    * @Description: 使用FileReader EileWriter可以实现文本文件的复制。
     * 对于非文本文件(视频文件、音频文件、图片),只能使用字节流!
    */
    @Test
    public void  testfileReaderwRITER(){
        //1,输入流对应的文件src一定要存在,否则抛异常,输出流对应的文件dest可以不存在,执行过程中会自动创至
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //不能实现非文本文件的复制
//            File src = new File("C:\Users\\shkstart\\Desktop\\1.jpg");
//            File dest = new File("C:\Users\\shkstart\\Desktop\3.jpg");
            File src = new File("hellow4.txt");
            File dest = new File("hellow5.txt");
            //2.
            fr = new FileReader(src);
            fw =new FileWriter(dest);
            //3.
            char[] c= new char[24];
            int len;
            while ((len = fr.read(c))!=-1){
                fw.write(c,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}

缓冲流(重点)

package testfile;

import org.junit.Test;

import java.io.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/10:02
 * @Description:
 *  * 2.IO的体系
 *  * 抽象基类
 *  * Inputstream
 *  * OutputStream
 *  * Reader
 *  * Writer
 *  * 节点流(文件流,开发不用)
 *  * Filelnputstream
 *  * FileOytputStream
 *  * FileReader
 *  * FileWriter
 *  * 缓冲流(处理流的一种,可以提升文件操作的效率,常用方法,效率高)
 *  * BufferedInputstream
 *  * BufferedOutputStream(.flush();)
 *  * BufferedReader:新增特殊方法readLine(),一次读一行)
 *  * Bufferedwriter(.flush();)
 */
public class testbuffer {

    @Test
    public void testbufferedReader(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            File file1 = new File("hellow5.txt");
            File file2 = new File("hellow6.txt");
            FileReader fr = new FileReader(file1);
            FileWriter fw = new FileWriter(file2);
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);

            //旧方法
//            char[] c = new char[1024];
//            int len;
//            while ((len=br.read(c))!=-1){
//                String str = new String(c,0,len);
//                System.out.println(str);
//            String str=null;
//            while ((str=br.readLine())!=null){
//                System.out.println(str);
//            }
            String str=null;
            while ((str=br.readLine())!=null){
                bw.write(str+"\n");
//                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br !=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (bw !=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }





    }
    @Test
    public void  testcopyfile(){
        long start = System.currentTimeMillis();
        String src="C:\\Users\\ming\\Desktop\\都不对.PNG";
        String des="C:\\Users\\ming\\Desktop\\都不对2.PNG";
        copyfile(src,des);
        long end = System.currentTimeMillis();
        System.out.println("花费的时间"+(end- start));



    }
    //使用缓冲流实现文件的复制的方法
    public void  copyfile(String src,String des){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1,提供读入、写出的文件
            File file1 = new File(src);
            File file2 = new File(des);
            //2.先创建相应的节点流FileinputStream、FileoutputStream
            FileInputStream fis =new FileInputStream(file1);
            FileOutputStream fos =new FileOutputStream(file2);
            //3,将创建的节点流的对象作为形参传递给缓冲流的构造器中
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //4,具体的实现文件复制的操作
            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b))!=-1){
                bos.write(b,0,len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭相应的流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
    //使用BufferedInputStream和BufferedoutputStream实现非文本g件的复制
    @Test
    public void testbufferinputoutputstream(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1,提供读入、写出的文件
            File file1 = new File("C:\\Users\\ming\\Desktop\\都不对.PNG");
            File file2 = new File("C:\\Users\\ming\\Desktop\\都不对2.PNG");
            //2.先创建相应的节点流FileinputStream、FileoutputStream
            FileInputStream fis =new FileInputStream(file1);
            FileOutputStream fos =new FileOutputStream(file2);
            //3,将创建的节点流的对象作为形参传递给缓冲流的构造器中
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //4,具体的实现文件复制的操作
            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b))!=-1){
                bos.write(b,0,len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭相应的流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }



}

实现字符流和字节流之间的转换,标准的输入输出流的使用

package testfile;

import org.junit.Test;

import java.io.*;
import java.util.Locale;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/10:55
 * @Description:
 */
public class testotherstream {
    /**
    * @Param: []
    * @return: void
    * @Author: ljm
    * @Date: 2021/4/5
    * @Description:
     * 如何实现字符流和字节流之间的转换
     * 转换流:InputStreamReader Ooutputstreamlriter
     * 编码:字符串-->字节数组
     * 解码:字节数组--->字符串
    */
    @Test
    public void testinputstreamreader(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //解码过程
            File file =new File("hellow4.txt");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis,"GBK");
            br = new BufferedReader(isr);
            //编码
            File file1 =new File("hellow41.txt");
            FileOutputStream fos = new FileOutputStream(file1);
            OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
            bw = new BufferedWriter(osw);
            String str;
            while ((str=br.readLine())!=null){
                bw.write(str);
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw!=null){

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


        }

    }
    /**
    * @Param:
    * @return:
    * @Author: ljm
    * @Date: 2021/4/5
    * @Description:
     * 标准的输入输出流
     * 标准的输出流:System.out
     * 标准的输入流:System.in
     *
     * 题目:从键盘输入字符串,要求将读取到的整行字符串转成大写输出。
     * 然后继续进行输入操作,直至当输入"e"或者"exit"时,退出程序。
    */
    @Test
    public void test2(){
        BufferedReader br = null;
        try {
            InputStream is = System.in;
            InputStreamReader isr =new InputStreamReader(is);
            br = new BufferedReader(isr);
            System.out.println("请输入字符串:");
            String str;
            while (true){
                str = br.readLine();
                if(str.equalsIgnoreCase("e")||str.equalsIgnoreCase("exit")){
                    break;
                }
                String str1 = str.toUpperCase(Locale.ROOT);
                System.out.println(str1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){

                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}

字符流输入输出复制

package testfile;

import org.junit.Test;

import java.io.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/15:39
 * @Description:
 */
public class testexe {
    //使用字符流实现内容输出
    @Test
    public void test1(){
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("test1.txt"));
            String str ="Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,\n"+
                    "是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和\n"+
                    "Java平台(即JavasE,JavaEE,JavaME)的总称.Java技术具有卓"+
            "越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台、"+
    "科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。在全球云计算"+
            "和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。";
            bw.write(str);
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


        }

    }
    //使用字符流实现内容的读入
    @Test
    public void test2(){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("test1.txt"));
            String str;
            while ((str=br.readLine())!=null){
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    @Test
    public void test3(){
        //利用字符流程序复制test1.txt为test2.1
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader("test1.txt"));
            bw = new BufferedWriter(new FileWriter("test2.txt"));

            char[] c = new char[20];
            int len;
            while ((len = br.read(c))!=-1){
                bw.write(c,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){

                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }



    }


}

数据流

package testfile;

import org.junit.Test;

import java.io.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/16:05
 * @Description:
 */
public class testother {
    //数据流:用来处理基本数据类型、String、字节数组的数据:DataInputstream Dataoutputstream
    @Test
    public void outprintStreamWriter(){
        DataOutputStream dos = null;
        try {
            FileOutputStream fos = new FileOutputStream("data.txt");
            dos = new DataOutputStream(fos);

            dos.writeUTF("我爱你,你在那里");
            dos.writeBoolean(true);
            dos.writeLong(1233445);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(dos!=null){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }

    @Test
    public void testDATA1(){
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(new File("data.txt")));
//            byte[] b = new byte[20];
//            int len;
//            while ((len=dis.read(b))!=-1){
//                System.out.println(new String(b,0,len));
//
//            }
           String str =  dis.readUTF();
            System.out.println(str);
            boolean b= dis.readBoolean();
            System.out.println(b);
            long c = dis.readLong();
            System.out.println(c);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(dis!=null){
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }


    }

}

对象流

package testfile;

import org.junit.Test;

import java.io.*;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/16:35
 * @Description:
 *
 */
public class testobjectinptoutput {

    //对象的序列化过程:将内存中的对象通过objectoutputstream转换为二进制流,存储在硬盘文件中
    @Test
    public void testobjectinptoutputstream(){
        person p1 = new person("xm",22);
        person p2 = new person("hm",21);

        ObjectOutputStream obj =null;
        try {
            obj = new ObjectOutputStream(new FileOutputStream("person.txt"));

            obj.writeObject(p1);
            obj.flush();
            obj.writeObject(p2);
            obj.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(obj!=null){
                try {
                    obj.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
    //对象的反序列化过程:将硬盘中的文件通过0bjectInputStream转换为相应的对象
    @Test
    public void testobjectinputstream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("person.txt"));
            person p1 = (person) ois.readObject();
            System.out.println(p1);
            person p2 = (person) ois.readObject();
            System.out.println(p2);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }




    }

}

/**
* @Param:
* @return:
* @Author: ljm
* @Date: 2021/4/5
* @Description:
 * //要实现序列化的类
 * 1,要求此类是可序列化的:实现Serializable接口
 * 2.对应类的属性同样实现Serializable接口
 * 3.提供一个版本号private static final long serialVersionUID = 23425124521L;
 * 4、使用static或transient修饰的属性,不可实现序列化
*/
class person implements Serializable {

    private static final long serialVersionUID = 23425124521L;

    String name;
    Integer age;

    public person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

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

RandomAccessFile读取、写入

package testfile;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/17:39
 * @Description:
 * RandomAccessFile:支持随机访问
 * 1,既可以充当一个输入流,有可以充当一个输出流
 * 2,支持从文件的开头读取、写入
 * 3·支持从任意位置的读取、写入(插入)
 */
public class testrandonaccess {
    //进行文件读写
    @Test
    public void test1(){
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("hellow5.txt"),"r");
            raf2 = new RandomAccessFile(new File("hellow9.txt"),"rw");
            int d;
            while ((d= raf1.read())!=-1){
                raf2.write(d);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf2!=null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf1!=null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }



    }
    //实现的实际上是覆盖的效果
    @Test
    public void test2(){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(new File("hellow3.txt"),"rw");
            raf.seek(3);
            raf.write("xy".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

//    在d字符后面插入"xy"
    @Test
    public void test3(){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(new File("hellow3.txt"),"rw");
            raf.seek(4);
            String str = raf.readLine();
//            long l = raf.getFilePointer();
//            System.out.println(l);
            raf.seek(4);
            raf.write("xy".getBytes());
            raf.write(str.getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
    //相交于test3更通用一些
    @Test
    public void test4(){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(new File("hellow3.txt"),"rw");
            raf.seek(4);
            byte[] b = new byte[10];
            int len;
            StringBuffer sb = new StringBuffer();
            while ((len = raf.read(b))!=-1){
                sb.append(new String(b,0,len));

            }
            raf.seek(4);
            raf.write("xy".getBytes());
            raf.write(sb.toString().getBytes());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }



}

线程

package testthread;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/20:13
 * @Description:
 * 创建一个子线程,完成1-100之间自然数的输出。
 * 同样地,主线程执行同样的操作创建多线程的第一种方式:继承java.lang.Thread类
 */
//1.创建一个继承于Thread的子类
class  subThread extends Thread{
    //2.重写Thread类的run()方法,方法内实现此子E要完成的功能
    public void run(){
        for(int i=1;i<=100;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }

}
public class TestThread {
    public static void main(String[] args) {
        //3.创建一个子类的对象
        subThread st =new subThread();
        subThread st1 =new subThread();
        //4,调用线程的start():启动此线程调用相应的run()方法
        //5、一个线程只能执行start()一次;
        //不能通过Thread实现类对象的run()去启动一个线程
        st.start();
        st1.start();

        for(int i=1;i<=100;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }

    }
}

package testthread;

import java.util.Map;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/20:48
 * @Description:
 *Thread的常用方法:
 * 1.start():启动线程并执行相应的run()方法2.run():子线程要执行的代码放入run()方法中
 * 3.currentThread():静态的,调取当前的线程
 * 4.getName():获取此线程的名字
 * 5.setName():设置此线程的名字
 * 6.yield():调用此方法的线程释放当前CPU的执行权
 * 7.join():在A线程中调用B线程的join()方法,
 * 表示:当执行到此方法,A线程停止执行,直至B线程执行完毕,A线程再接着join()之后的代码执行
 * 8.isAlive():判断当前线程是否还存活
 * 9.sleep(long L):显式的让当前线程睡眠L毫秒
 * 10.线程通信:wait() notify() notifyAll()
 *
 * 设置线程的优先级
 * getPriority():返回线程优先值
 * setPriority(int newPriority):改变线程的优先级
 */
class subThread1 extends Thread{
    //2.重写Thread类的run()方法,方法内实现此子E要完成的功能
    public void run(){
        for(int i=1;i<=100;i++){
            System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);
        }
    }

}
public class testthread1 {
    public static void main(String[] args) {
        //3.创建一个子类的对象
        subThread1 st =new subThread1();
        subThread1 st1 =new subThread1();

        st1.setPriority(Thread.MAX_PRIORITY);

        //4,调用线程的start():启动此线程调用相应的run()方法
        //5、一个线程只能执行start()一次;
        //不能通过Thread实现类对象的run()去启动一个线程
        st.start();
        st1.start();

        for(int i=1;i<=100;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}

package testthread;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/21:53
 * @Description:
 * /创建多线程的方式二:通过实现的方式
 *
 *
 *对比一下继承的方式vs实现的方式
 * 1·联系:public class Thread implements Runnable
 * 2,哪个方式好?实现的方式优于继承的方式why?@避免了java单继承的局限性
 * @如果多个线程要操作同一份资源(或数据),更适合使用实现的方式
 */
//1.创建一个实现了Runnable接口的类
class printnum1 implements Runnable{
    //2.实现接口的抽象方法
    @Override
    public void run() {
        //子线程执行的代码
        for(int i=0;i<=100;i++) {
            if(i%2==0){
                System.out.println(Thread.currentThread().getName()+":"+i);

            }

        }

    }
}
public class testThread2 {
    public static void main(String[] args) {
        //3.创建一个Runnable接口实现类的对象
        printnum1 p = new printnum1();
        //要想启动一个多线程,必须调用start()
        //4,将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
        Thread t1= new Thread(p);
        //5,调用start()方法:启动线程并执行run()
        t1.start();//启动线程;执行Thread对象生成时构造器形参的对象的run()方法。

        //再创建一个线程
        Thread t2 = new Thread(p);
        t2.start();

    }


}

同步锁机制和同步方法

同步锁机制

package testthread;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/22:09
 * @Description:
 * 此程序存在线程的安全问题:打印车票时,会出现重票、错票1,线程安全问题存在的原因?
 * 由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。
 * 2.如何来解决线程的安全问题?
 * 必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。
 * 3.java如何实现线程的安全:线程的同步机制
 * 方式一,同步代码块
 * synchronized(同步监视器){
 * //需要被同步的代码块(即为操作共享数据的代码)
 * }
 * 1,共享数据:多个线程共同操作的同一个数据(变量)
 * 2,同步监视器,由一个类的对象来充当。哪个缚程获取此监视器,谁就执行大括号里被同步的代码。俗称;锁
 * 要求:所有的线程必须共用同一把锁!
 * 注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this
 * 方式二:同步方法
 *
 */

class windows1 implements Runnable{
    int ticket= 100;//共享数据
    //锁可以由任何类的对象充当
    //Object obj = new Object();


    @Override
    public void run() {
        while (true){
            synchronized (this){//this表示当前对象,本题中为w1
            if(ticket>0){
                try {
                    Thread.currentThread().sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"售票:票号为"+ticket--);
            }else {
                break;
            }

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

        windows1  w1 = new windows1();
        Thread t11= new Thread(w1);
        Thread t21= new Thread(w1);
        Thread t31= new Thread(w1);

        t11.setName("窗口1");
        t21.setName("窗口2");
        t31.setName("窗口3");

        t11.start();
        t21.start();
        t31.start();

    }





}
}

同步方法

package testthread;

/**
 * @Auther: ljm
 * @Date: 2021/04/05/22:09
 * @Description:
 * 此程序存在线程的安全问题:打印车票时,会出现重票、错票1,线程安全问题存在的原因?
 * 由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。
 * 2.如何来解决线程的安全问题?
 * 必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。
 * 3.java如何实现线程的安全:线程的同步机制
 * 方式一,同步代码块
 * synchronized(同步监视器){
 * //需要被同步的代码块(即为操作共享数据的代码)
 * }
 * 1,共享数据:多个线程共同操作的同一个数据(变量)
 * 2,同步监视器,由一个类的对象来充当。哪个缚程获取此监视器,谁就执行大括号里被同步的代码。俗称;锁
 * 要求:所有的线程必须共用同一把锁!
 * 注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this
 *
 * 方式二:同步方法
 * 将操作共享数据的方法声明为synchronized.
 * 即此方法为同步方法,能够保证当其中一个线程执行此方法时,其它线程在外等待直至此线程执行完此方法。
 *>同步方法的锁:this
 */

class windows2 implements Runnable{
    int ticket= 100;//共享数据
    //锁可以由任何类的对象充当
    //Object obj = new Object();

    public synchronized void show(){
        if(ticket>0){
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"售票:票号为"+ticket--);
        }

    }

    @Override
    public void run() {
        while (true){
            show();
        }

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

        windows2 w1 = new windows2();
        Thread t11= new Thread(w1);
        Thread t21= new Thread(w1);
        Thread t31= new Thread(w1);

        t11.setName("窗口1");
        t21.setName("窗口2");
        t31.setName("窗口3");

        t11.start();
        t21.start();
        t31.start();

    }





}
}

线程的通信

package testthread;

/**
 * @Auther: ljm
 * @Date: 2021/04/06/17:45
 * @Description:
 * 生产者/消费者问题
 * 生产者(Productor)将产品交给店员(Clerk),
 * 而消费者(customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,
 * 店员会叫生产者停一下如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,
 * 如果店中有产品了再通知消费者来取走产品。
 *
 * 分析:
 * 1,是否涉及到多线程的问题?是!生产者、消费者
 * 2,是否涉及到共享数据?有!考虑线程的安全
 * 3,此共享数据是谁?即为产品的数量
 * 4·是否涉及到线程的通信呢?存在这生产者与消费者的通信
 */

class cleck{//店员
    int product;

    public synchronized void addproduct(){//生存产品
        if(product>=20){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            product++;
            System.out.println(Thread.currentThread().getName()+":"+"生存了第"+product+"个产品");
            notifyAll();
        }

    }

    public synchronized void consumeproduct(){//消费产品
        if (product<=0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println(Thread.currentThread().getName()+":"+"生存了第"+product+"个产品");
            product--;
            notifyAll();
        }

    }


}
class producter implements Runnable{//生产者

    cleck cleck;

    public producter(testthread.cleck cleck) {
        this.cleck = cleck;
    }

    @Override
    public void run() {
        System.out.println("生产者开始生产产品");
        while(true){
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cleck.addproduct();
        }

    }
}

class consumer implements Runnable{

    cleck cleck;

    public consumer(testthread.cleck cleck) {
        this.cleck = cleck;
    }

    @Override
    public void run() {
        System.out.println("消费商品");
        while (true){
            cleck.consumeproduct();
        }

    }
}
public class testproduct {
    public static void main(String[] args) {
        cleck cleck =new cleck();
        producter p1 = new producter(cleck);
        consumer c1 = new consumer(cleck);

        Thread T1 = new Thread(p1);//生产者线程
        Thread T3 = new Thread(p1);//生产者线程
        Thread T2 = new Thread(c1);//消费者线程

        T1.setName("生产者1");
        T3.setName("生产者2");
        T2.setName("消费者");

        T1.start();
        T2.start();



    }
}

字符串转换

import org.junit.Test;

/**
 * @Auther: ljm
 * @Date: 2021/04/06/22:06
 * @Description:
 * *1,字符串与基本数据类型、包装类之间转换
 * *①字符串--->基本数据类型、包装类:调用相应的包装类的parsexxx(string str);
 * *②基本数据类型、包装类--->字符串:调用字符串的重载的valueof()方法网
 * *2.字符串与字节教组间的转换
 * *①字符串---->字节数组:调用字符串的getBytes()
 * *②字节数组-->字符串:调用字符串的构造器
 * *
 * *3.字符串与字符数组间的转换
 * ①字符串---->字符数组:调用字符串的toCharArray();
 * ②字符数组---->字符串:调用字符串的构造器
 */
public class teststring {
    @Test
    public void test5(){

        //1,字符串与基本数据类型、包装类之间转换
        String str1 ="123";
        int i = Integer.parseInt(str1);
        System.out.println(i);
        String str2 =i+"";
        str2 = String.valueOf(i);
        System.out.println(str2);
        System.out.println();

        //2.字符串与字节数组间的转换
        String str="abcd123";
        byte[] b = str.getBytes();
        for(int j=0;j<b.length;j++){
        System.out.println((char)b[j]);
        }
        String str3 = new String(b);
        System.out.println(str3);

        //3、字符串与字符数组间的转换
        String str4 ="abc主公";
        char[] c = str4.toCharArray();
        for(int j=0;j<c.length;j++){
            System.out.println(c[j]);
        }
        String str5 = new String(c);
        System.out.println(str5);


    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值