java基础和高级进阶(2)

104 阅读15分钟

几个类的方法

1.system类

image-20210915101419869

image-20210915103218804

package MySystem;public class MySystem { 
    public static void main(String[] args) {
        //        System.out.println("开始");//
        System.exit(0);//   
        System.out.println("结束");//  
        System.out.println(System.currentTimeMillis()*1.0/1000/60/60/24/365+"年"); 
        long start = System.currentTimeMillis();      
        for (int i = 0; i < 10000; i++) { 
            System.out.println(i);     
        }   
        long end = System.currentTimeMillis(); 
        System.out.println((end-start)+"毫秒");   
    }
}

2.object类

1.toString

image-20210915103754738

image-20210915104740789

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

2.equals

@Override  
public boolean equals(Object o) {  
    if (this == o) return true;
    // 先比较地址是否相同     
    if (!(o instanceof Student)) return false; 
    //参数是否为null并且是否来自同一个类   
    Student student = (Student) o;
    //类型转换,从Object转到Student   
    return this.age == student.age && Objects.equals(this.name, student.name); 
}

3.Arrays类

1.冒泡排序

image-20210915112518404

package MyObject;
import java.util.ArrayList;
import java.util.List;
import  java.util.Scanner;
public class bulubulu {    
    public static void main(String[] args) { 
        int num,a=1;    
        List<Integer> list = new ArrayList<Integer>();      
        Scanner sc = new Scanner(System.in);  
        while((num = sc.nextInt() )!= 0){
            list.add(num);    
        }  
        System.out.println(list.toString());  
        System.out.println("___________________");  
        System.out.println("开始冒泡排序");    
        while(a != list.size()-1){      
            int v1,v2,temp;         
            for (int i = 0; i < list.size()-1; i++) {  
                v1=list.get(i);      
                v2=list.get(i+1);        
                if(v1>v2){               
                    temp = v1;             
                    list.set(i, list.get(i+1));    
                    list.set(i+1,temp);     
                }        
            }        
            a++;   
        }  
        System.out.println(list.toString());
    }
}

2.Arrays

image-20210915112650019

image-20210915113959126

package MyObject;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class bulubulu {    public static void main(String[] args) {        int num,a=1;        int[] list1 = {1,4,4,6,34,2};        List<Integer> list = new ArrayList<Integer>();        Scanner sc = new Scanner(System.in);        while((num = sc.nextInt() )!= 0){            list.add(num);        }        System.out.println(list.toString());        System.out.println(Arrays.toString(list1));        System.out.println("___________________");        System.out.println("开始冒泡排序");        while(a != list.size()-1){            int v1,v2,temp;            for (int i = 0; i < list.size()-1; i++) {                v1=list.get(i);                v2=list.get(i+1);                if(v1>v2){                    temp = v1;                    list.set(i, list.get(i+1));                    list.set(i+1,temp);                }            }            a++;        }        System.out.println(list.toString());        Arrays.sort(list1);        System.out.println(Arrays.toString(list1));    }}

4.基本类型包装类

1.Integer

image-20210915114413635

image-20210915114523985

2.int 和 String 的相互转换

package MyParcel;public class MyInterger { 
    public static void main(String[] args) {
        int num = 100;      
        String str;    
        str = String.valueOf(num);
        System.out.println(str);
        str = "100";        
        num = Integer.parseInt(str);   
        System.out.println(num); 
    }
}

3.字符串里的数据排序,StringBuilder

public class Mysort {
    public static void main(String[] args) {
        String str = "23 4 5 43 56";
        String[] strings = str.split(" ");//切割字符串
        int[] num = new int[strings.length];
        for (int i = 0; i <num.length; i++) {
            num[i] = Integer.parseInt(strings[i]);
        }
        Arrays.sort(num);

//        循环输出
        for (int i = 0; i < num.length; i++) {
            System.out.print(num[i]+" ");
        }
        System.out.println();

//        变成字符串,调用方法输出
        String result = Arrays.toString(num);
        System.out.println(result);

//        使用StringBuilder拼接输出
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num.length; i++) {
            if(i == num.length-1){
                sb.append(num[i]);
            }else{
                sb.append(num[i]).append(" ");
            }
        }

        String str2 = sb.toString();
        System.out.println(str2);
    }
}

4.自动装箱和拆箱

函数名用途
valueof装箱
intValue拆箱

image-20210917173429846

5.日期类

函数名作用
Date生成日期
getTime获取日期
setTime设置日期格式
SimpleDateFormat日期模式显示
formatdata->string
parsestring->data
calendar日历
calendar.add修改日历时间
package MyObject;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDate {
    public static void main(String[] args) throws ParseException {

//        构造Date
        System.out.println("构造Date");
        Date date = new Date();
        System.out.println(date);
//        重构
        long time = 1000*60*60;
        Date date1 = new Date(time);
        System.out.println(date1);

//        日期的get和set方法
        System.out.println("日期的get和set方法");
        Date date2 = new Date();
        System.out.println((int)(date2.getTime()*1.0/1000/60/60/24/365)+"年");

        Date date3 = new Date();
        date3.setTime(time);
        System.out.println(date3);

//        日期的模式显示
        System.out.println("日期的模式显示");
        Date date4 = new Date();
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
        String dat =dataFormat.format(date4);
        System.out.println(dat);

        String strTime = "2021-9-17 18:56:34";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        Date date5 = simpleDateFormat.parse(strTime);
        System.out.println(date5);
    }
}

日历

public class MyCandler {
    public static void main(String[] args) {
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int month = calendar.get(Calendar.MONTH)+1;
//        int day = calendar.get(Calendar.DATE);

//        System.out.println(year+"年"+month+"月"+day+"日");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR,10);
        calendar.add(Calendar.DATE,-5);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DATE);
        System.out.println(year+"年"+month+"月"+day+"日");
    }
}

二月多少天

public class TwoMonth {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int year = sc.nextInt();

        Calendar calendar = Calendar.getInstance();
        calendar.set(year,2,1);
        calendar.add(Calendar.DATE,-1);
        int day = calendar.get(calendar.DATE);
        System.out.println(year+"年的二月有:"+day+"天");
    }
}

异常

函数名作用
try , catch接收异常
getMessage获取异常信息
toString异常信息的字符串化
printStackTrace打印所有的异常信息

image-20210917202942980

1.异常处理

image-20210917204440634

package MyThow;public class MyThrow {
    public static void main(String[] args) {
        System.out.println("开始");
        Test();
        System.out.println("结束");
    } 
    public static void Test(){
        try { 
            int[] num  ={1,2,3}; 
            System.out.println(num[8]);  
        } catch (ArrayIndexOutOfBoundsException e) {
            // 
            System.out.println("访问的数组越界");  
            System.out.println(e.getMessage());  
            System.out.println(e.toString());      
            e.printStackTrace();  
        }  
    }
}

2.异常的区别

image-20210917204737959

3.throws异常抛出

image-20210917205615942

image-20210917205638467

4.自定义异常

image-20210917205754543

package MyThow;public class MyException extends Exception{
    public MyException() { 
    }  
    public MyException(String message) {  
        super(message); 
    }
}
package MyThow;import java.util.Scanner;public class MyBug { 
    public static void main(String[] args)throws MyException {  
        Scanner sc = new Scanner(System.in); 
        int num = sc.nextInt();   
        Test(num); 
    }   
    public static void Test(int sroce) throws MyException{  
        if(sroce>100){    
            throw new MyException("你输入的分数大于100,错误");  
        }      
        else {  
            System.out.println(sroce);   
        } 
    }
}

#集合

image-20210918153902174

1.Collection :ArrayList

Collection的接口实现类
List(不能用Collection多态创建)
ArrayList(可以用List多态创建)
LinkedList
函数名作用
Collection<> c = new ArrayList多态创建
c.add添加
c.size大小
c.remove移除指定元素
c.clear清空
c.isEmpty为空
Iterator <> it = c.iterator迭代器
it.next下一个元素
it.hasNext为空

image-20210918154055950

image-20210918155702642

public class CollectionTest {
    public static void main(String[] args) {
        Collection<Integer> collection = new ArrayList<Integer>();

        collection.add(23);
        collection.add(2);
        collection.add(32);

        System.out.println(collection);
//      遍历
        Iterator<Integer> it = collection.iterator();
//        for (int i = 0; i < collection.size(); i++) {
//            System.out.println(it.next());
//        }

        //        方法二:
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

}

2.List : ArrayList 和 LinkedList

方法名作用
List<> list = new ArrayList<>();创建
add添加
get获取
set对现有的元素修改

public class ListTest {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(34);
        list.add(1,12);
        System.out.println(list);//34,12

        list.remove(1);
        System.out.println(list);//34

        list.set(0,3);//只能对现有的元素进行修改
        System.out.println(list.get(0));

        System.out.println("----------------");
        list.add(45);
        list.add(9);
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) System.out.println(it.next());


        System.out.println("---------------");


        ListIterator<Integer> it1 = list.listIterator();
        while (it1.hasNext())it1.next();
        while(it1.hasPrevious()){
            System.out.println(it1.previous());

        }

        System.out.println("---------------");

        for (Integer integer : list) {
            System.out.println(integer);
        }
    }

}

1.ListIterator

列表特有的迭代器

image-20210918162915862

2.并发修改异常

image-20210918162539160

每一次add一个数据都会增加modCount;

但是当用户在迭代时进行对集合的添加,会造成modCount的增加但是并没有更新预期修改次数,这时就会抛出异常。

###3.增强for语句

for (Integer integer : list) {    System.out.println(integer);}

4.ArrayList 和 LinkedList

一个是普通存储,一个是链表

image-20210918165554387

image-20210918170242129

public class LinkList {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        System.out.println("头插:");
        list.addFirst(12);
        System.out.println(list);
        System.out.println("尾插: ");
        list.addLast(34);
        System.out.println(list);

        System.out.println("第一个元素:"+list.getFirst());
        System.out.println("最后一个元素: "+list.getLast());

        System.out.println("删除第一个元素后: ");
        list.removeFirst();
        System.out.println(list);
    }
}

3.Set : HashSet

Set的接口实现类
HsahSet
LinkedHashSet
TreeSet

image-20210918171013794

public class SetTest {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<Integer>();

        set.add(23);
        set.add(45);
        set.add(2);

        for (Integer integer : set) {
            System.out.println(integer);
        }
    }
}

4.哈希值

image-20210918172040224

image-20210918172034287

5.HashSet

###HashSet对于元素唯一性分析

image-20210918173432377

image-20210918173542774

哈希表

image-20210918184812628

LinkedHashSet

image-20210918185053987

TreeSet

image-20210918185415194

自然排序Comparable : 对于要进行排序的类:Student。。。。

image-20210918190850346

public class TreeSetTest {
    public static void main(String[] args) {
        Student student = new Student(12,"dd");
        Student student1 = new Student(34,"Dc");
        Student student2 = new Student(5,"223");
        TreeSet<Student> set = new TreeSet<>();
        set.add(student);
        set.add(student1);
        set.add(student2);

        for (Student s : set) {
            System.out.println(s.getAge()+"  "+s.getName());
        }
    }
}

比较器排序

image-20210918191320019

6.泛型

image-20210920154851064

image-20210920160616570

如果不添加则while里面的it就是一个Object类型,需要强制类型转换,并且,如果在输入数据的时候输入了其他的类型,在强转是就会有异常。

1.泛型类

image-20210920162116631

public class GenericT<T>{ 
    T t;   
    public GenericT(T t) {
        this.t = t;  
    }  
    public T getT() {
        return t;  
    }  
    public void setT(T t) { 
        this.t = t; 
    }
}
public class GenTest {
    public static void main(String[] args) {

        Student student = new Student("张振",12);
        Teacher teacher = new Teacher("王老师",23);

        System.out.println(student.getName());
        System.out.println(teacher.getName());

        System.out.println("----------------");

        GenericT<String> genericT = new GenericT<>("张三");
        System.out.println(genericT.getT());

        GenericT<Integer> genericT1 = new GenericT<>(23);
        System.out.println(genericT1.getT());


    }
}

2.泛型方法

image-20210920162719315

public class GenericT2 { 
    public <T>void show(T t){ 
        System.out.println(t);
    }
}
public class Test2 {
    public static void main(String[] args) {  
        GenericT2 g = new GenericT2();
        g.show(12);     
        g.show("你好"); 
        g.show(12.3342342);  
    }
}

3.泛型接口

image-20210920163507275

接口

public interface Gen<T> {  
    void show(T t);
}

实现类

public class GenImpl<T> implements Gen<T>{
    @Override 
    public void show(T t){  
        System.out.println(t); 
    }
}

调用

Gen<String> gen = new GenImpl<>();gen.show("sdad");

###4.类型通配符

image-20210920165055582

5.可变参数

a相当于一个数组,一个方法包含多个参数时,可变参数要放在最后

image-20210920170814687

public class ChangTest {    public static void main(String[] args) {        System.out.println(sum(12,1,1,1,1,1,1));        System.out.println(sum(23,12,33,3));    }    public static int sum(int b,int...a){        int sum = 0;        for (int i : a) {            sum+=0;        }        return b<sum ? sum : b ;    }

6.可变参数的使用

接口和工具类函数名用处
Arrays工具类asList返回固定位置的list集合(不可再次修改)
List接口List.of()返回任意可重复,增删改都不可以
Set接口of返回不可重复的集合,增删改都不可以

image-20210920171114918

image-20210920172148720

image-20210920173235864

public class OfTest {  
    public static void main(String[] args) {   
        List<Integer> list = Arrays.asList(1,2,3,4,5,3);     
        System.out.println(list);    
        Set<String> strings = Set.of("121","word","haha");  
        System.out.println(strings);    
        try {            
            Set<String> strings1 = Set.of("121","word","haha","121");  
            System.out.println(strings);   
        } catch (Exception e) {        
            
            System.out.println("出现重复元素,Set不允许");  
        }  
    }
}

7.Map集合

image-20210921192344710

image-20210921192831490

public class Map01 {  
    public static void main(String[] args) { 
        Map<Integer,String> map = new HashMap<>(); 
        map.put(12,"你好");       
        map.put(13,"HashMap");    
        System.out.println(map);  
        map.put(13,"替代了旧的,保留了键的唯一性"); 
        System.out.println(map);
    }
}

###1.Map集合的基本功能

方法名作用
put添加元素
remove根据键值删除元素
clear清空Map
containsKey是否包含指定键
containsValue是否包含指定值
isEmpty是否为空
size大小

image-20210921194142023

public class Map02 {
    public static void main(String[] args) {
        Map<Integer,String>map = new HashMap<>();

        map.put(1,"你好");
        map.put(2,"时间");
        map.put(3,"哈哈");
        map.put(4,"中秋节快乐");

        System.out.println(map);

        map.remove(2);
        System.out.println("删除指定键");
        System.out.println(map);

        System.out.println(map.containsKey(2)? "有" : "没有");
        System.out.println(map.containsValue("中秋节快乐")? "有" : "没有");

        System.out.println("map的大小:"+map.size());
        System.out.println("是否为空: "+(map.isEmpty()? "为空" : "不为空"));
        map.clear();
        System.out.println("map的大小:"+map.size());
        System.out.println("是否为空: "+(map.isEmpty()? "为空" : "不为空"));
    }
}

2.Map集合的获取

方法名作用
get通过键,得到键值
KeySet返回所有的键,形成Set集合
values返回所有的键值,形成可重复的Collection集合
entrySet获取所有键值对对象的集合,之后用get分别拿值

image-20210921194934658

public class Map03 {
    public static void main(String[] args) {
        Map<Integer,String> map = new HashMap<>();

        map.put(1,"你好");
        map.put(2,"时间");
        map.put(3,"哈哈");
        map.put(4,"中秋节快乐");

        System.out.println(map);
        System.out.println("1的值:"+map.get(1));

        System.out.println("--------------");
        System.out.println("用Set存储Map的键,然后增强for");
        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            System.out.println(map.get(integer));
        }

        System.out.println("--------------");
        System.out.println("用Collection存储Map的键值,然后增强for");
        Collection<String> collection = map.values();
        for (String s : collection) {
            System.out.println(s);
        }
    }
}

3.Map集合的遍历

  • 方法一:

    用keySet方法转化成Set集合,然后遍历

  • 方法二:

    获取所有键值对对象的集合

    image-20210921200114371

    public static void main(String[] args) {  
        Map<Integer,String> map = new HashMap<>();   
        map.put(1,"你好"); 
        map.put(2,"时间");    
        map.put(3,"哈哈");   
        
        map.put(4,"中秋节快乐");  
        //获取所有键值对对象的集合 
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for (Map.Entry<Integer, String> me : entries) { 
            int a = me.getKey();
            //拿值   
            String name = me.getValue();
            System.out.println(a+" "+name); 
        }
    }
    

###4.存储学生类

image-20210921200911879

public class Map05 {
    public static void main(String[] args) {
        Map<String, Student> studentMap = new HashMap<>();
        Student student1 = new Student("张三",12);
        Student student2 = new Student("李四",45);
        Student student3 = new Student("王五",33);

        studentMap.put("20201391108",student1);
        studentMap.put("20201391111",student2);
        studentMap.put("20201391123",student3);

        System.out.println("方式一的遍历: ");

        Set<String> strings = studentMap.keySet();
        for (String s : strings) {
            System.out.println(studentMap.get(s).getName()+" "+studentMap.get(s).getAge());
        }

        System.out.println("--------------");
        System.out.println("方式二遍历");
        Set<Map.Entry<String, Student>> set = studentMap.entrySet();
        for (Map.Entry<String, Student> entry : set) {
            System.out.println(entry.getKey()+" "+entry.getValue().getAge()+" "+entry.getValue().getName());
        }
    }
}

5.ArrayList存储多个Map集合

image-20210921202228457

public class Map06 {
    public static void main(String[] args) {
        ArrayList<Map<Integer,String>> arrayList = new ArrayList<>();

        Map<Integer,String> map1 = new HashMap<>();
        map1.put(1,"qw");
        map1.put(2,"sad");
        arrayList.add(map1);

        Map<Integer,String> map2 = new HashMap<>();
        map2.put(3,"fg");
        map2.put(4,"f");
        arrayList.add(map2);

        for (Map<Integer, String> map : arrayList) {
            Set<Integer> set = map.keySet();
            for (Integer integer : set) {
                System.out.println(map.get(integer));
            }
            System.out.println("下一个:");
        }
    }
}

8.Collections

方法名作用
sort升序排序
reverse翻转顺序
shuffle随机打乱

image-20210922205848327

public class Collections01 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(12);
        list.add(3);
        list.add(121);
        list.add(56);

        System.out.println(list.toString());
        System.out.println("接下来是升序:  ");
        Collections.sort(list);
        System.out.println(list.toString());
        System.out.println("接下来是翻转:  ");
        Collections.reverse(list);
        System.out.println(list);
        System.out.println("接下来是随机打乱:  ");
        Collections.shuffle(list);
        System.out.println(list);
    }
}

###Collections的应用:加上自然排序的:new Comparator,内部构造

image-20210922211629239

public class Collections02 {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        Student student = new Student(12,"asdjnad");
        Student student1 = new Student(12,"asdas");
        Student student2 = new Student(4,"ASd");
        Student student3 = new Student(64,"ASdsxx");
        Student student4 = new Student(34,"ASdwed");

        students.add(student);
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);

        for (Student stu : students) {
            System.out.println(stu.getAge()+" "+stu.getName());
        }

        System.out.println("--------------");
        System.out.println("接下来是自然排序");

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getAge()- o2.getAge();
                int nums = num==0 ? o1.getName().compareTo(o2.getName()) : num;
                return nums;
            }
        });

        for (Student stu : students) {
            System.out.println(stu.getAge()+" "+stu.getName());
        }
    }
}

IO流模块

1.File

###1.1.构造方法

image-20210923085657176

image-20210923090249776

public class File01 {
    public static void main(String[] args) {
        System.out.println("--------------Test01------------");
        File file = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest.txt");
        System.out.println(file);
        System.out.println("--------------Test02------------");
        File file1 = new File("C:\\Users\\gui\\Desktop\\java笔记","javaTest.txt");
        System.out.println(file1);
        System.out.println("--------------Test03------------");
        File file2 = new File("C:\\Users\\gui\\Desktop\\java笔记");
        File file3 = new File(file2,"javaTest.txt");
        System.out.println(file3);
    }
}

1.2.创建功能

image-20210923090357232

image-20210923091351502image-20210923091402917image-20210923091417157image-20210923091514662

public class File02 {
    public static void main(String[] args) throws IOException {
//          创建文件
        File file = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest","javaTest.txt");
        System.out.println(file.createNewFile()? "成功ture" : "false失败,已存在");

        File file1 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest","javaTest.txt");
        System.out.println(file1.createNewFile()? "成功ture" : "false失败,已存在");

//         创建目录
        File file2 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest01");
        System.out.println(file2.mkdir()? "成功ture" : "false失败,已存在");

//        创建多级目录
        File file3 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest02\\javaTest0201");
        System.out.println(file3.mkdirs()? "成功ture" : "false失败,已存在");

    }
}

###1.3.判断和获取功能

方法名作用
isDirectory()路径是否为目录
isFile()路径是否为文件
exists()是否存在
getAbsolutePath()返回绝对路径名的字符串
getPath()返回路径名字符串
getName()返回路径名表示的文件或目录名称
list()文件或目录名称数组
listFiles()文件或目录的File对象数组

image-20210923093526545

image-20210923093149330

public class File03 {
    public static void main(String[] args) {
        System.out.println("路径是否为目录:");
        File file = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest01");
        System.out.println(file.isDirectory()?"是":"不是");

        System.out.println("路径是否为文件:");
        File file1 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\javaTest.txt");
        System.out.println(file1.isFile()?"是":"不是");

        System.out.println("是否存在");
        File file2 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\javaTest.txt");
        System.out.println(file2.exists()?"是":"不是");

        System.out.println("返回绝对路径名的字符串");
        File file3 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\javaTest.txt");
        System.out.println(file3.getAbsolutePath());

        System.out.println("返回路径名字符串");
        File file4 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\javaTest.txt");
        System.out.println(file4.getPath());

        System.out.println("返回路径名表示的文件或目录名称");
        File file5 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\javaTest.txt");
        System.out.println(file5.getName());

        System.out.println("文件或目录名称数组");
        File file6 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest");
        String[] list = file6.list();
        for (String s : list) {
            System.out.println(s);
        }

        System.out.println("文件或目录名称数组");
        File file7 = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest");
        File[] files = file7.listFiles();
        for (File f : files) {
            System.out.println(f.getName());
        }
    }
}

1.4.删除功能

image-20210923093247844

image-20210923095354383

image-20210923095402894

public class File04 {
    public static void main(String[] args) throws IOException {
        System.out.println("创建文件和目录:");
        File file = new File("myFile");
        System.out.println(file.mkdir());
        File file1 = new File("myFile//javaTest.txt");
        System.out.println(file1.createNewFile());

        System.out.println("删除文件:");
        System.out.println(file1.delete());

        File file2 = new File("myFile//haha");
        System.out.println(file2.mkdir());

        System.out.println("删除目录:");
        System.out.println(file2.delete());
    }
}

2.递归遍历目录

image-20210923184433193

public class File05 {
    public static void main(String[] args) {
//        创建File
        File srcFile  =new File("C:\\Users\\gui\\Desktop\\java笔记");
        getFile(srcFile);

    }
    public static void getFile(File file){
        File[] files = file.listFiles();
        if(files != null){
            for (File f : files) {
                if(f.isFile()){
                    getFile(f);
                }
                else {
                    System.out.println(f.getPath());
                }
            }
        }
    }
}

3.字节流

image-20210923184853504

1.Output

方法作用
FileOutputStream创建输出字节流对象
write写入一个字节,一个字节数组,一个字节数组的一部分
close释放资源

image-20210923191053954

image-20210923191259575

public class OutPut {
    public static void main(String[] args) throws IOException {
        FileOutputStream file = new FileOutputStream("myFile\\TEXT.txt",true);

//        一个字节:
        file.write(97);
        file.write("\n".getBytes());
//        一个字节数组
        byte[] bytes = {97,98,99,100,101,102,103,104};
        file.write(bytes);
        file.write("\n".getBytes());

//        字节数组的一部分
        file.write(bytes,3,4);
        file.close();
    }
}

2.字节流写数据加异常处理

image-20210923192219609

image-20210923192811036


public class OutPut02 {
    public static void main(String[] args) {
        FileOutputStream file = null;
        try {
            file = new FileOutputStream("w:\\Users\\gui\\Desktop\\java笔记\\javaTest");
            try {
                file.write(99);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.Input

方法作用
FileIntputStream创建输入字节流对象
read读取一个字节
close释放资源

image-20210923193533590

public class Input {
    public static void main(String[] args) {
        int by;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("myFile\\TEXT.txt");
            while((by = fileInputStream.read()) != -1){
                System.out.print((char)by);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.读和写实现文本复制


public class IOTest {
    public static void main(String[] args) throws IOException {
        FileInputStream rwrite = new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\滕王阁序.txt");
        FileOutputStream write = new FileOutputStream("myFile\\滕王阁序.txt");

        int by;
        while((by = rwrite.read())!=-1){
            write.write(by);
        }

        rwrite.close();
        write.close();
    }
}

5.一次读取字节数组

image-20210923195154268

public class Input02 {
    public static void main(String[] args) throws IOException {
        FileInputStream filet = new FileInputStream("myFile\\TEXT.txt");

        int len;
        byte[] bytes = new byte[5];
        while((len = filet.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
    }
}

6.复制图片

image-20210923195557593

public class IOPhoto {
    public static void main(String[] args) throws IOException {
        FileInputStream rwrite = new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\Test.png");
        FileOutputStream write = new FileOutputStream("MyFile\\Test.png");

        int by;
        while ((by = rwrite.read()) != -1){
            write.write(by);
        }
        rwrite.close();
        write.close();
    }
}

7.字节缓冲流

image-20210923195845917

public class BufferedIO {
    public static void main(String[] args) throws IOException {
        FileInputStream rwrite = new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\滕王阁序.txt");
        BufferedInputStream bI = new BufferedInputStream(rwrite);
        FileOutputStream write = new FileOutputStream("myFile\\滕王阁序1.txt");
        BufferedOutputStream bO = new BufferedOutputStream(write);

        bO.write(bI.read());
        rwrite.close();
        write.close();
    }
}

8.输入输出的比较

image-20210923202822579


public class BufferedIOTest {
    public static void main(String[] args) throws IOException {
        System.out.println("字节流一次读一个");
        long star = System.currentTimeMillis();
        method1();
        long end = System.currentTimeMillis();
        System.out.println((end - star) + "毫秒");

        System.out.println("字节流一次读一个数组");
        long star2 = System.currentTimeMillis();
        method2();
        long end2 = System.currentTimeMillis();
        System.out.println(end2 - star2 + "毫秒");

        System.out.println("字节缓冲流一次读一个");
        long star3 = System.currentTimeMillis();
        method3();
        long end3 = System.currentTimeMillis();
        System.out.println(end3 - star3 + "毫秒");

        System.out.println("字节缓冲流一次读一个数组");
        long star4 = System.currentTimeMillis();
        method4();
        long end4 = System.currentTimeMillis();
        System.out.println(end4 - star4 + "毫秒");
    }

    public static void method1() throws IOException {
        FileInputStream rwrite = new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\Test.png");
        FileOutputStream write = new FileOutputStream("myFile\\Test1.png");
        int by;
        while ((by = rwrite.read()) != -1) {
            write.write(by);
        }
        rwrite.close();
        write.close();
    }

    public static void method2() throws IOException {
        FileInputStream rwrite = new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\Test.png");
        FileOutputStream write = new FileOutputStream("myFile\\Test2.png");
        int len;
        byte[] bytes = new byte[1024];
        while ((len = rwrite.read(bytes)) != -1) {
            write.write(bytes, 0, 1024);
        }
        rwrite.close();
        write.close();
    }

    public static void method3() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\Test.png"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myFile\\Test3.png"));
        int by;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }
        bis.close();
        bos.close();
    }

    public static void method4() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\gui\\Desktop\\java笔记\\Test.png"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myFile\\Test4.png"));
        int len;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, 1024);
        }
        bis.close();
        bos.close();
    }
}

4.字符流

1.编码表

image-20210924143631979

image-20210924143815912

2.字符串的编码解码规则:使用到Arrays类的方法

image-20210924144803879

public class Code {  
    public static void main(String[] args) throws UnsupportedEncodingException {   
        String s = "我爱中国";     
        byte[] bytes = s.getBytes("UTF-8");    
        System.out.println("UTF-8的: ");   
        System.out.println(Arrays.toString(bytes)); 
        System.out.println("GBK的: ");      
        byte [] bytes1 = s.getBytes("GBK");  
        System.out.println(Arrays.toString(bytes1)); 
        System.out.println("UTF-8的: ");       
        System.out.println(new String(bytes,"UTF-8"));   
        System.out.println("GBK的: ");    
        System.out.println(new String(bytes,"GBK"));
    }
}

3.字符流的编码解码规则

public class Code2 {  
    
    public static void main(String[] args) throws IOException {  
        OutputStreamWriter osw = new OutputStreamWriter(newFileOutputStream("myFile\\Test01.txt"),"UTF-8");  
        osw.write("我爱中国");     
        osw.close();   
        InputStreamReader isr = new InputStreamReader(new FileInputStream("myFile\\滕王阁序.txt"));      
        int len;      
        char[] ch = new char[2];    
        while ((len=isr.read(ch))!=-1){
            System.out.print(ch);
        }        
        isr.close();   
    }
}

4.字符流写数据的五种方式

由于是字符流:需要刷新才能进去:flush方法。

image-20210924152053886

image-20210924153130947

image-20210924153054080

public class CharStream01 {
    public static void main(String[] args) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myFile\\Test01.txt",true));
//        字符
        osw.write('\n');
        osw.write('9');
        osw.write('\n');
//        字符数组
        char[]chars = {'q','2','d'};
        osw.write(chars);
        osw.write('\n');
//        字符串
        osw.write("sdasdsadas");
        osw.write('\n');


//        字符串一部分
        osw.write("12345678",0,4);
        osw.write('\n');
        osw.close();
    }
}

5.字符流读取数据

image-20210924153156949

public class CharStream02 {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("myFile\\Test01.txt"));

        System.out.println("一个一个的:");
        int ch;
        while ((ch = isr.read())!= -1){
            System.out.print((char)ch);
        }

        System.out.println("一组一组的:");
        int len;
        char[] chars = new char[1024];
        while((len = isr.read(chars))!= -1){
            System.out.println(new String(chars,0,len));
        }

        isr.close();
    }
}

6.字符缓冲流

image-20210924154912997

public class BufferedChar01 {
    public static void main(String[] args) throws IOException {
        BufferedWriter bfw = new BufferedWriter(new FileWriter("myFile\\Test.txt",true));
        bfw.write("我爱你中国");
        bfw.close();

        BufferedReader bfr = new BufferedReader(new FileReader("myFile\\Test.txt"));
        int ch;
        while((ch = bfr.read())!= -1){
            System.out.print((char) ch);
        }
        bfw.close();
    }
}

7.字符缓冲流的特有功能

方法名作用
newLine()写一行行分隔符,自动匹配系统
readLine()读一行文字,返回字符串,不包含换行符

image-20210924160446434

public class BufferedChar02 {
    public static void main(String[] args) throws IOException {
        BufferedWriter bfw = new BufferedWriter(new FileWriter("myFile\\Test.txt"));
        for (int i = 0; i < 10; i++) {
            bfw.write("你好"+i);
            bfw.newLine();
        }
        bfw.flush();
        bfw.close();

        BufferedReader BFR = new BufferedReader(new FileReader("myFile\\Test.txt"));

        String s;
        while((s = BFR.readLine())!= null)
        System.out.println(s);
    }
}

5.集合到文件

image-20210924164537771


public class Test {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入要创建几个学生");
        int count = sc.nextInt();
        ArrayList<Student> students = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            System.out.println("依次输入姓名和成绩:");
            Student student = new Student(sc.next(),sc.nextInt(), sc.nextInt(), sc.nextInt());
            students.add(student);
        }
        students.sort(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getSum()-s2.getSum();
                int num2 = num==0?s1.getYin().compareTo(s2.getYin()):num;
                return num2;
            }
        });

        BufferedWriter bfw = new BufferedWriter(new FileWriter("myFile\\Student.txt"));
        for (Student student : students) {
            String s = student.getName()+","+student.getYu()+","+student.getSu()+","+student.getYin();
            bfw.write(s);
            bfw.newLine();
            bfw.flush();
        }
        bfw.close();
    }
}

6.IO流小结

image-20210924160730872

image-20210924160827121

7.几个案例

1.复制单目录

image-20210925164428811


public class Test02 {
    public static void main(String[] args) throws IOException {
        File srcFolder = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest");//源文件
        String name = srcFolder.getName();
        File destFolder = new File("myCharStream",name);//目的地文件
        if (!destFolder.exists()){
            destFolder.mkdirs();
            System.out.println("创建成功");
        }

        File[] files = srcFolder.listFiles();
        for (File fileInt : files) {//源文件
            String names = fileInt.getName();
            File fileOut = new File(destFolder,names);//目的地文件
            copyFile(fileInt,fileOut);
        }

    }

    public static void copyFile(File intt , File out) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(intt));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(out));
        int len;
        byte[]bytes = new byte[1024];
        while((len = bis.read(bytes))!=-1){
            bos.write(bytes);
        }
        bis.close();
        bos.close();
    }
}

2.复制多级

image-20210925172726018


public class Test03 {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("C:\\Users\\gui\\Desktop\\java笔记\\javaTest02");//创建源文件
        File destFile = new File("myCharStream1");//创建目的地,是最先一级的
        getFile(srcFile,destFile);
    }

    public static void getFile(File srcFile,File destFile) throws IOException {
        if(srcFile.isDirectory()){
            String name = srcFile.getName();//获取文件名
            File newFile = new File(destFile,name);
            if(!newFile.exists()){
                newFile.mkdir();//创建多级目录
            }
            File[] files = srcFile.listFiles();//获取一级目录下的二级文件
            for (File file : files) {
                getFile(file, newFile);//file是先一级目录下的二级目录,newFile是地址
            }
        }
        else{
            File out = new File(destFile,srcFile.getName());
            copyFile(srcFile,out);
        }

    }
    public static void copyFile(File intt , File out) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(intt));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(out));
        int len;
        byte[]bytes = new byte[1024];
        while((len = bis.read(bytes))!=-1){
            bos.write(bytes);
        }
        bis.close();
        bos.close();
    }
}

8.复制文件的异常抛出处理

image-20210927151200695

public class Test04 {
    public static void main(String[] args) {
        method01();
    }

    //    普通的异常处理
    public static void method01(){
        BufferedWriter bfw = null;
        BufferedReader bfr = null;
        try {
           bfw = new BufferedWriter(new FileWriter("myFile\\Test02.txt"));
           bfr = new BufferedReader(new FileReader("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\滕王阁序.txt"));
           int ch;
           while ((ch = bfr.read()) != -1) {
               bfw.write((char) ch);
           }
        } catch (IOException e) {
           e.printStackTrace();
        } finally {
           if(bfw!=null){
               try {
                   bfw.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if(bfr!=null){
               try {
                   bfr.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }

        }
    }
//    jdk7的异常处理
    public static void method02(){
        try(BufferedWriter bfw = new BufferedWriter(new FileWriter("myFile\\Test02.txt"));
            BufferedReader bfr = new BufferedReader(new FileReader("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\滕王阁序.txt"));
            ) {
            int ch;
            while((ch=bfr.read())!=-1){
                bfw.write((char)ch);
            }
            bfw.flush();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

//    jdk9的异常处理
public static void method03() throws IOException {
    BufferedWriter bfw = new BufferedWriter(new FileWriter("myFile\\Test02.txt"));
    BufferedReader bfr = new BufferedReader(new FileReader("C:\\Users\\gui\\Desktop\\java笔记\\javaTest\\滕王阁序.txt"));
    try(bfw;bfr) {
        int ch;
        while((ch=bfr.read())!=-1){
            bfw.write((char)ch);
        }
        bfw.flush();
    }
    catch (IOException e){
        e.printStackTrace();
    }
}
}

9.标准输入输出流

image-20210927161517803

image-20210927164117444

public class IO01 {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));//System.in返回的是InputStream
        PrintStream out = System.out;

        System.out.println("请输入字符串: ");
        String line = bfr.readLine();
        System.out.println("你输入的字符串是: "+line);
        out.println("你输入的字符串是: "+line);

        System.out.println("请输入一个整数");
        Integer num = Integer.valueOf(bfr.readLine());
        System.out.println("你输入的整数是: "+num.intValue());
        out.println("你输入的整数是: "+num.intValue());
    }
}

10.打印流

###1.字节打印流

image-20210927165037056


public class IO02 {
    public static void main(String[] args) throws IOException {
        PrintStream ps = new PrintStream("myFile\\Test.txt");

        ps.write(97);
        ps.println();
        ps.println("hhhhhh");
        ps.println(1213213);

        ps.flush();
        ps.close();
    }
}

2.字符打印流

image-20210927165846388

public class IO03 {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter(new FileWriter("myFile\\Test.txt"),true); 
        pw.println("hello");
        pw.println("world");
        pw.write("\r\n"+"hahahahahaha");
        pw.flush();
        pw.close();
    }}

11.对象序列化流与反序列化

###1.序列化

注意:要给对象实现一个接口: Serializable , 这个接口不需要重写方法

image-20210927170249421

image-20210927184310728

public class IO04 {
    public static void main(String[] args) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myFile\\Test03.txt"));
        Student student = new Student("小明",22);
        
        oos.writeObject(student); 
        oos.flush(); 
        oos.close(); 
    }
}

2.反序列化

image-20210927184739110

image-20210927184928326

public class IO04 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {        ObjectOutputStream oos = new ObjectOutputStream(new      FileOutputStream("myFile\\Test03.txt"));
                                                                                       Student student = new Student("小明",22);
                                                                                  oos.writeObject(student); 
                                                                                       oos.flush(); 
                                                                                       oos.close();  
                                                                                       ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myFile\\Test03.txt"));        Student student1 = (Student) ois.readObject();   
                                                                                       System.out.println(student1.toString());
                                                                                      }
}

3.对象序列化的三个问题

image-20210927185025836

image-20210927190121908

private static final long serialVersionUID = 42L;
private  transient int sorce;

12.properties

###1.作为map集合使用

image-20210927191546484
public class Properties01 { 
    public static void main(String[] args) {
        Properties pr = new Properties();
        pr.put("001","张三"); 
        pr.put("003","李四"); 
        pr.put("005","王五"); 
        Set<Object> set = pr.keySet();
        //存储的是pr里的key , 也可以用pr.values()来返回一个Collection集合
        for (Object s : set) {
            Object value = pr.get(s); 
            System.out.println(s+","+value);
        }  
    }
}

2.特有方法

image-20210927191711045

image-20210927192924531

public class properties02 {
    public static void main(String[] args) {  
        Properties pr = new Properties(); 
        pr.put("001","张三");    
        pr.put("003","李四");    
        pr.put("005","王五");    
        pr.setProperty("009","新来滴");  
        String s1 = pr.getProperty("001");  
        System.out.println(s1);   
        String s2 = pr.getProperty("023"); 
        System.out.println((s2==null? "无" : "有"));   
        Set<String> strings = pr.stringPropertyNames();  
        for (String key : strings) {    
            
            String values = pr.getProperty(key);  
            System.out.println(key+","+values); 
        }   
    }
}

3.与IO流结合

image-20210927193010920

image-20210927193906816

image-20210927193921843

public class properties03 { 
    public static void main(String[] args) throws IOException {
        Properties pr = new Properties();    
        pr.put("001","张三");  
        pr.put("003","李四");
        pr.put("005","王五"); 
        pr.setProperty("009","新来滴"); 
        FileWriter os = new FileWriter("myFile\\Test04.txt");   
        pr.store(os,null);     
        Properties properties = new Properties(); 
        FileReader rs = new FileReader("myFile\\Test04.txt"); 
        properties.load(rs);
        rs.close();      
        System.out.println(properties);
    
    }
}

4.案例:游戏次数

image-20210927202514460

public class Properties04 {
    public static void main(String[] args) throws IOException {
//        创建游戏文件
        FileWriter fos = new FileWriter("MyFile\\geam.txt");
//        初始化数值:
        int count = 0;
        Properties ps = new Properties();
        String games = String.valueOf(count);
        ps.put("1",games);
//        创建游戏:
        RandomGeam(fos,ps,count);
    }

    public static void RandomGeam(FileWriter fos , Properties ps,int count) throws IOException{
        FileReader reader = new FileReader("MyFile\\geam.txt");
        Scanner sc = new Scanner(System.in);
        System.out.println("你想玩游戏吗: ");
        String cs;
        while((cs = sc.next()).equals("想")){
            if(count>=3){
                System.out.println("你的游戏场次不够了,请找桂爷爷充值,是否充值: ");
                if(sc.next().equals("是")){
                    System.out.println("去吧");
                }
                System.out.println("没钱还玩游戏,run吧");
                break;
            }
            Random random = new Random();
            int num = random.nextInt(3);
            System.out.println("请输入你要猜的数: ");
            int younum = sc.nextInt();
            while(younum != num){
                if(younum > num){
                    System.out.println("猜错了,数值大了,请重新输入:");
                    System.out.println("请输入你要猜的数: ");
                    younum = sc.nextInt();
                }
                else if(younum < num){
                    System.out.println("猜错了,数值小了,请重新输入:");
                    System.out.println("请输入你要猜的数: ");
                    younum = sc.nextInt();
                }
            }

            ++count;
            String games = String.valueOf(count);
            ps.put("1",games);
            ps.store(fos,null);
            int c = Integer.parseInt(ps.getProperty("1"));
            System.out.println("恭喜你,猜对了,你现在的游戏场次是: "+c);
            System.out.println("你想玩游戏吗: ");
        }
        System.out.println("不玩了是吧,拜拜");
    }
}