小白想学学java——————6

1.Map集合

1.1Map集合概述和特点【理解】

  • Map集合概述

    interface Map<K,V>  K:键的类型;V:值的类型
    
  • Map集合的特点

    • 键值对映射关系
    • 一个键对应一个值
    • 键不能重复,值可以重复
    • 元素存取无序
  • Map集合的基本使用

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
    
            //V put(K key, V value) 将指定的值与该映射中的指定键相关联
            map.put("itheima001","林青霞");
            map.put("itheima002","张曼玉");
            map.put("itheima003","王祖贤");
            map.put("itheima003","柳岩");
    
            //输出集合对象
            System.out.println(map);
        }
    }
    

1.2Map集合的基本功能【应用】

  • 方法介绍

    方法名说明
    V put(K key,V value)添加元素
    V remove(Object key)根据键删除键值对元素
    void clear()移除所有的键值对元素
    boolean containsKey(Object key)判断集合是否包含指定的键
    boolean containsValue(Object value)判断集合是否包含指定的值
    boolean isEmpty()判断集合是否为空
    int size()集合的长度,也就是集合中键值对的个数
  • 示例代码

    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
    
            //V put(K key,V value):添加元素
            map.put("张无忌","赵敏");
            map.put("郭靖","黄蓉");
            map.put("杨过","小龙女");
    
            //V remove(Object key):根据键删除键值对元素
    //        System.out.println(map.remove("郭靖"));
    //        System.out.println(map.remove("郭襄"));
    
            //void clear():移除所有的键值对元素
    //        map.clear();
    
            //boolean containsKey(Object key):判断集合是否包含指定的键
    //        System.out.println(map.containsKey("郭靖"));
    //        System.out.println(map.containsKey("郭襄"));
    
            //boolean isEmpty():判断集合是否为空
    //        System.out.println(map.isEmpty());
    
            //int size():集合的长度,也就是集合中键值对的个数
            System.out.println(map.size());
    
    
            //输出集合对象
            System.out.println(map);
        }
    }
    

1.3Map集合的获取功能【应用】

  • 方法介绍

    方法名说明
    V get(Object key)根据键获取值
    Set keySet()获取所有键的集合
    Collection values()获取所有值的集合
    Set<Map.Entry<K,V>> entrySet()获取所有键值对对象的集合
  • 示例代码

    public class MapDemo03 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //V get(Object key):根据键获取值
    //        System.out.println(map.get("张无忌"));
    //        System.out.println(map.get("张三丰"));
    
            //Set<K> keySet():获取所有键的集合
    //        Set<String> keySet = map.keySet();
    //        for(String key : keySet) {
    //            System.out.println(key);
    //        }
    
            //Collection<V> values():获取所有值的集合
            Collection<String> values = map.values();
            for(String value : values) {
                System.out.println(value);
            }
        }
    }
    

1.4Map集合的遍历(方式1)【应用】

  • 遍历思路

    • 我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
      • 把所有的丈夫给集中起来
      • 遍历丈夫的集合,获取到每一个丈夫
      • 根据丈夫去找对应的妻子
  • 步骤分析

    • 获取所有键的集合。用keySet()方法实现
    • 遍历键的集合,获取到每一个键。用增强for实现
    • 根据键去找值。用get(Object key)方法实现
  • 代码实现

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //获取所有键的集合。用keySet()方法实现
            Set<String> keySet = map.keySet();
            //遍历键的集合,获取到每一个键。用增强for实现
            for (String key : keySet) {
                //根据键去找值。用get(Object key)方法实现
                String value = map.get(key);
                System.out.println(key + "," + value);
            }
        }
    }
    

1.5Map集合的遍历(方式2)【应用】

  • 遍历思路

    • 我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
      • 获取所有结婚证的集合
      • 遍历结婚证的集合,得到每一个结婚证
      • 根据结婚证获取丈夫和妻子
  • 步骤分析

    • 获取所有键值对对象的集合
      • Set<Map.Entry<K,V>> entrySet():获取所有键值对对象的集合
    • 遍历键值对对象的集合,得到每一个键值对对象
      • 用增强for实现,得到每一个Map.Entry
    • 根据键值对对象获取键和值
      • 用getKey()得到键
      • 用getValue()得到值
  • 代码实现

    public class MapDemo02 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String, String> map = new HashMap<String, String>();
    
            //添加元素
            map.put("张无忌", "赵敏");
            map.put("郭靖", "黄蓉");
            map.put("杨过", "小龙女");
    
            //获取所有键值对对象的集合
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            //遍历键值对对象的集合,得到每一个键值对对象
            for (Map.Entry<String, String> me : entrySet) {
                //根据键值对对象获取键和值
                String key = me.getKey();
                String value = me.getValue();
                System.out.println(key + "," + value);
            }
        }
    }
    

1.6Map集合的案例【应用】

1.6.1HashMap集合练习之键是String值是Student
  • 案例需求

    ​ 创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      /*
          需求:
              创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
      
          思路:
              1:定义学生类
              2:创建HashMap集合对象
              3:创建学生对象
              4:把学生添加到集合
              5:遍历集合
                  方式1:键找值
                  方式2:键值对对象找键和值
       */
      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<String, Student> hm = new HashMap<String, Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put("itheima001", s1);
              hm.put("itheima002", s2);
              hm.put("itheima003", s3);
      
              //方式1:键找值
              Set<String> keySet = hm.keySet();
              for (String key : keySet) {
                  Student value = hm.get(key);
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
              System.out.println("--------");
      
              //方式2:键值对对象找键和值
              Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
              for (Map.Entry<String, Student> me : entrySet) {
                  String key = me.getKey();
                  Student value = me.getValue();
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
          }
      }
      
1.6.2HashMap集合练习之键是Student值是String
  • 案例需求

    • 创建一个HashMap集合,键是学生对象(Student),值是居住地 (String)。存储多个元素,并遍历。
    • 要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
      
              Student student = (Student) o;
      
              if (age != student.age) return false;
              return name != null ? name.equals(student.name) : student.name == null;
          }
      
          @Override
          public int hashCode() {
              int result = name != null ? name.hashCode() : 0;
              result = 31 * result + age;
              return result;
          }
      }
      
    • 测试类

      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<Student, String> hm = new HashMap<Student, String>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
              Student s4 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put(s1, "西安");
              hm.put(s2, "武汉");
              hm.put(s3, "郑州");
              hm.put(s4, "北京");
      
              //遍历集合
              Set<Student> keySet = hm.keySet();
              for (Student key : keySet) {
                  String value = hm.get(key);
                  System.out.println(key.getName() + "," + key.getAge() + "," + value);
              }
          }
      }
      
1.6.3集合嵌套之ArrayList嵌套HashMap
  • 案例需求

    • 创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap
    • 每一个HashMap的键和值都是String,并遍历。
  • 代码实现

    public class ArrayListIncludeHashMapDemo {
        public static void main(String[] args) {
            //创建ArrayList集合
            ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
    
            //创建HashMap集合,并添加键值对元素
            HashMap<String, String> hm1 = new HashMap<String, String>();
            hm1.put("孙策", "大乔");
            hm1.put("周瑜", "小乔");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm1);
    
            HashMap<String, String> hm2 = new HashMap<String, String>();
            hm2.put("郭靖", "黄蓉");
            hm2.put("杨过", "小龙女");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm2);
    
            HashMap<String, String> hm3 = new HashMap<String, String>();
            hm3.put("令狐冲", "任盈盈");
            hm3.put("林平之", "岳灵珊");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm3);
    
            //遍历ArrayList集合
            for (HashMap<String, String> hm : array) {
                Set<String> keySet = hm.keySet();
                for (String key : keySet) {
                    String value = hm.get(key);
                    System.out.println(key + "," + value);
                }
            }
        }
    }
    
1.6.4集合嵌套之HashMap嵌套ArrayList
  • 案例需求

    • 创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList
    • 每一个ArrayList的元素是String,并遍历。
  • 代码实现

    public class HashMapIncludeArrayListDemo {
        public static void main(String[] args) {
            //创建HashMap集合
            HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
    
            //创建ArrayList集合,并添加元素
            ArrayList<String> sgyy = new ArrayList<String>();
            sgyy.add("诸葛亮");
            sgyy.add("赵云");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("三国演义",sgyy);
    
            ArrayList<String> xyj = new ArrayList<String>();
            xyj.add("唐僧");
            xyj.add("孙悟空");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("西游记",xyj);
    
            ArrayList<String> shz = new ArrayList<String>();
            shz.add("武松");
            shz.add("鲁智深");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("水浒传",shz);
    
            //遍历HashMap集合
            Set<String> keySet = hm.keySet();
            for(String key : keySet) {
                System.out.println(key);
                ArrayList<String> value = hm.get(key);
                for(String s : value) {
                    System.out.println("\t" + s);
                }
            }
        }
    }
    
1.6.5统计字符串中每个字符出现的次数
  • 案例需求

    • 键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
    • 举例:键盘录入“aababcabcdabcde” 在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
  • 代码实现

    public class HashMapDemo {
        public static void main(String[] args) {
            //键盘录入一个字符串
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串:");
            String line = sc.nextLine();
    
            //创建HashMap集合,键是Character,值是Integer
    //        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
            TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();
    
            //遍历字符串,得到每一个字符
            for (int i = 0; i < line.length(); i++) {
                char key = line.charAt(i);
    
                //拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
                Integer value = hm.get(key);
    
                if (value == null) {
                    //如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
                    hm.put(key,1);
                } else {
                    //如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
                    value++;
                    hm.put(key,value);
                }
            }
    
            //遍历HashMap集合,得到键和值,按照要求进行拼接
            StringBuilder sb = new StringBuilder();
    
            Set<Character> keySet = hm.keySet();
            for(Character key : keySet) {
                Integer value = hm.get(key);
                sb.append(key).append("(").append(value).append(")");
            }
    
            String result = sb.toString();
    
            //输出结果
            System.out.println(result);
        }
    }
    

2.Collections集合工具类

2.1Collections概述和使用【应用】

  • Collections类的作用

    ​ 是针对集合操作的工具类

  • Collections类常用方法

    方法名说明
    public static void sort(List list)将指定的列表按升序排序
    public static void reverse(List<?> list)反转指定列表中元素的顺序
    public static void shuffle(List<?> list)使用默认的随机源随机排列指定的列表
  • 示例代码

    public class CollectionsDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            List<Integer> list = new ArrayList<Integer>();
    
            //添加元素
            list.add(30);
            list.add(20);
            list.add(50);
            list.add(10);
            list.add(40);
    
            //public static <T extends Comparable<? super T>> void sort(List<T> list):将指定的列表按升序排序
    //        Collections.sort(list);
    
            //public static void reverse(List<?> list):反转指定列表中元素的顺序
    //        Collections.reverse(list);
    
            //public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表
            Collections.shuffle(list);
    
            System.out.println(list);
        }
    }
    

2.2ArrayList集合存储学生并排序【应用】

  • 案例需求

    • ArrayList存储学生对象,使用Collections对ArrayList进行排序
    • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      public class CollectionsDemo02 {
          public static void main(String[] args) {
              //创建ArrayList集合对象
              ArrayList<Student> array = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("linqingxia", 30);
              Student s2 = new Student("zhangmanyu", 35);
              Student s3 = new Student("wangzuxian", 33);
              Student s4 = new Student("liuyan", 33);
      
              //把学生添加到集合
              array.add(s1);
              array.add(s2);
              array.add(s3);
              array.add(s4);
      
              //使用Collections对ArrayList集合排序
              //sort(List<T> list, Comparator<? super T> c)
              Collections.sort(array, new Comparator<Student>() {
                  @Override
                  public int compare(Student s1, Student s2) {
                      //按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
                      int num = s1.getAge() - s2.getAge();
                      int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                      return num2;
                  }
              });
      
              //遍历集合
              for (Student s : array) {
                  System.out.println(s.getName() + "," + s.getAge());
              }
          }
      }
      

3.斗地主案例

3.1模拟斗地主案例-普通版本【应用】

  • 案例需求

    ​ 通过程序实现斗地主过程中的洗牌,发牌和看牌

  • 代码实现

    public class PokerDemo {
        public static void main(String[] args) {
            //创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
            ArrayList<String> array = new ArrayList<String>();
    
            //往牌盒里面装牌
            /*
                ♦2,♦3,♦4...♦K,♦A
                ♣2,...
                ♥2,...
                ♠2,...
                小王,大王
             */
            //定义花色数组
            String[] colors = {"♦", "♣", "♥", "♠"};
            //定义点数数组
            String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
            for (String color : colors) {
                for (String number : numbers) {
                    array.add(color + number);
                }
            }
            array.add("小王");
            array.add("大王");
    
            //洗牌,也就是把牌打撒,用Collections的shuffle()方法实现
            Collections.shuffle(array);
    
    //        System.out.println(array);
    
            //发牌,也就是遍历集合,给三个玩家发牌
            ArrayList<String> lqxArray = new ArrayList<String>();
            ArrayList<String> lyArray = new ArrayList<String>();
            ArrayList<String> fqyArray = new ArrayList<String>();
            ArrayList<String> dpArray = new ArrayList<String>();
    
            for (int i = 0; i < array.size(); i++) {
                String poker = array.get(i);
                if (i >= array.size() - 3) {
                    dpArray.add(poker);
                } else if (i % 3 == 0) {
                    lqxArray.add(poker);
                } else if (i % 3 == 1) {
                    lyArray.add(poker);
                } else if (i % 3 == 2) {
                    fqyArray.add(poker);
                }
            }
    
            //看牌,也就是三个玩家分别遍历自己的牌
            lookPoker("林青霞", lqxArray);
            lookPoker("柳岩", lyArray);
            lookPoker("风清扬", fqyArray);
            lookPoker("底牌", dpArray);
        }
    
        //看牌的方法
        public static void lookPoker(String name, ArrayList<String> array) {
            System.out.print(name + "的牌是:");
            for (String poker : array) {
                System.out.print(poker + " ");
            }
            System.out.println();
        }
    }
    

3.2模拟斗地主案例-升级版本【应用】

  • 案例需求

    ​ 通过程序实现斗地主过程中的洗牌,发牌和看牌。要求:对牌进行排序

  • 代码实现

    public class PokerDemo {
        public static void main(String[] args) {
            //创建HashMap,键是编号,值是牌
            HashMap<Integer, String> hm = new HashMap<Integer, String>();
    
            //创建ArrayList,存储编号
            ArrayList<Integer> array = new ArrayList<Integer>();
    
            //创建花色数组和点数数组
            String[] colors = {"♦", "♣", "♥", "♠"};
            String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
    
            //从0开始往HashMap里面存储编号,并存储对应的牌。同时往ArrayList里面存储编号
            int index = 0;
    
            for (String number : numbers) {
                for (String color : colors) {
                    hm.put(index, color + number);
                    array.add(index);
                    index++;
                }
            }
            hm.put(index, "小王");
            array.add(index);
            index++;
            hm.put(index, "大王");
            array.add(index);
    
            //洗牌(洗的是编号),用Collections的shuffle()方法实现
            Collections.shuffle(array);
    
            //发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
            TreeSet<Integer> lqxSet = new TreeSet<Integer>();
            TreeSet<Integer> lySet = new TreeSet<Integer>();
            TreeSet<Integer> fqySet = new TreeSet<Integer>();
            TreeSet<Integer> dpSet = new TreeSet<Integer>();
    
            for (int i = 0; i < array.size(); i++) {
                int x = array.get(i);
                if (i >= array.size() - 3) {
                    dpSet.add(x);
                } else if (i % 3 == 0) {
                    lqxSet.add(x);
                } else if (i % 3 == 1) {
                    lySet.add(x);
                } else if (i % 3 == 2) {
                    fqySet.add(x);
                }
            }
    
            //调用看牌方法
            lookPoker("林青霞", lqxSet, hm);
            lookPoker("柳岩", lySet, hm);
            lookPoker("风清扬", fqySet, hm);
            lookPoker("底牌", dpSet, hm);
        }
    
        //定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
        public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
            System.out.print(name + "的牌是:");
            for (Integer key : ts) {
                String poker = hm.get(key);
                System.out.print(poker + " ");
            }
            System.out.println();
        }
    }
    

1.File类

1.1File类概述和构造方法【应用】

  • File类介绍

    • 它是文件和目录路径名的抽象表示
    • 文件和目录是可以通过File封装成对象的
    • 对于File而言,其封装的并不是一个真正存在的文件,仅仅是一个路径名而已。它可以是存在的,也可以是不存在的。将来是要通过具体的操作把这个路径的内容转换为具体存在的
  • File类的构造方法

    方法名说明
    File(String pathname)通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
    File(String parent, String child)从父路径名字符串和子路径名字符串创建新的 File实例
    File(File parent, String child)从父抽象路径名和子路径名字符串创建新的 File实例
  • 示例代码

    public class FileDemo01 {
        public static void main(String[] args) {
            //File(String pathname):通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
            File f1 = new File("E:\\itcast\\java.txt");
            System.out.println(f1);
    
            //File(String parent, String child):从父路径名字符串和子路径名字符串创建新的 File实例。
            File f2 = new File("E:\\itcast","java.txt");
            System.out.println(f2);
    
            //File(File parent, String child):从父抽象路径名和子路径名字符串创建新的 File实例。
            File f3 = new File("E:\\itcast");
            File f4 = new File(f3,"java.txt");
            System.out.println(f4);
        }
    }
    

1.2File类创建功能【应用】

  • 方法分类

    方法名说明
    public boolean createNewFile()当具有该名称的文件不存在时,创建一个由该抽象路径名命名的新空文件
    public boolean mkdir()创建由此抽象路径名命名的目录
    public boolean mkdirs()创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录
  • 示例代码

    public class FileDemo02 {
        public static void main(String[] args) throws IOException {
            //需求1:我要在E:\\itcast目录下创建一个文件java.txt
            File f1 = new File("E:\\itcast\\java.txt");
            System.out.println(f1.createNewFile());
            System.out.println("--------");
    
            //需求2:我要在E:\\itcast目录下创建一个目录JavaSE
            File f2 = new File("E:\\itcast\\JavaSE");
            System.out.println(f2.mkdir());
            System.out.println("--------");
    
            //需求3:我要在E:\\itcast目录下创建一个多级目录JavaWEB\\HTML
            File f3 = new File("E:\\itcast\\JavaWEB\\HTML");
    //        System.out.println(f3.mkdir());
            System.out.println(f3.mkdirs());
            System.out.println("--------");
    
            //需求4:我要在E:\\itcast目录下创建一个文件javase.txt
            File f4 = new File("E:\\itcast\\javase.txt");
    //        System.out.println(f4.mkdir());
            System.out.println(f4.createNewFile());
        }
    }
    

1.3File类判断和获取功能【应用】

  • 判断功能

    方法名说明
    public boolean isDirectory()测试此抽象路径名表示的File是否为目录
    public boolean isFile()测试此抽象路径名表示的File是否为文件
    public boolean exists()测试此抽象路径名表示的File是否存在
  • 获取功能

    方法名说明
    public String getAbsolutePath()返回此抽象路径名的绝对路径名字符串
    public String getPath()将此抽象路径名转换为路径名字符串
    public String getName()返回由此抽象路径名表示的文件或目录的名称
    public String[] list()返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
    public File[] listFiles()返回此抽象路径名表示的目录中的文件和目录的File对象数组
  • 示例代码

    public class FileDemo04 {
        public static void main(String[] args) {
            //创建一个File对象
            File f = new File("myFile\\java.txt");
    
    //        public boolean isDirectory():测试此抽象路径名表示的File是否为目录
    //        public boolean isFile():测试此抽象路径名表示的File是否为文件
    //        public boolean exists():测试此抽象路径名表示的File是否存在
            System.out.println(f.isDirectory());
            System.out.println(f.isFile());
            System.out.println(f.exists());
    
    //        public String getAbsolutePath():返回此抽象路径名的绝对路径名字符串
    //        public String getPath():将此抽象路径名转换为路径名字符串
    //        public String getName():返回由此抽象路径名表示的文件或目录的名称
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getPath());
            System.out.println(f.getName());
            System.out.println("--------");
    
    //        public String[] list():返回此抽象路径名表示的目录中的文件和目录的名称字符串数组
    //        public File[] listFiles():返回此抽象路径名表示的目录中的文件和目录的File对象数组
            File f2 = new File("E:\\itcast");
    
            String[] strArray = f2.list();
            for(String str : strArray) {
                System.out.println(str);
            }
            System.out.println("--------");
    
            File[] fileArray = f2.listFiles();
            for(File file : fileArray) {
    //            System.out.println(file);
    //            System.out.println(file.getName());
                if(file.isFile()) {
                    System.out.println(file.getName());
                }
            }
        }
    }
    

1.4File类删除功能【应用】

  • 方法分类

    方法名说明
    public boolean delete()删除由此抽象路径名表示的文件或目录
  • 示例代码

    public class FileDemo03 {
        public static void main(String[] args) throws IOException {
    //        File f1 = new File("E:\\itcast\\java.txt");
            //需求1:在当前模块目录下创建java.txt文件
            File f1 = new File("myFile\\java.txt");
    //        System.out.println(f1.createNewFile());
    
            //需求2:删除当前模块目录下的java.txt文件
            System.out.println(f1.delete());
            System.out.println("--------");
    
            //需求3:在当前模块目录下创建itcast目录
            File f2 = new File("myFile\\itcast");
    //        System.out.println(f2.mkdir());
    
            //需求4:删除当前模块目录下的itcast目录
            System.out.println(f2.delete());
            System.out.println("--------");
    
            //需求5:在当前模块下创建一个目录itcast,然后在该目录下创建一个文件java.txt
            File f3 = new File("myFile\\itcast");
    //        System.out.println(f3.mkdir());
            File f4 = new File("myFile\\itcast\\java.txt");
    //        System.out.println(f4.createNewFile());
    
            //需求6:删除当前模块下的目录itcast
            System.out.println(f4.delete());
            System.out.println(f3.delete());
        }
    }
    
  • 绝对路径和相对路径的区别

    • 绝对路径:完整的路径名,不需要任何其他信息就可以定位它所表示的文件。例如:E:\itcast\java.txt
    • 相对路径:必须使用取自其他路径名的信息进行解释。例如:myFile\java.txt

2.递归

2.1递归【应用】

  • 递归的介绍

    • 以编程的角度来看,递归指的是方法定义中调用方法本身的现象
    • 把一个复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解
    • 递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算
  • 递归的基本使用

    public class DiGuiDemo {
        public static void main(String[] args) {
            //回顾不死神兔问题,求第20个月兔子的对数
            //每个月的兔子对数:1,1,2,3,5,8,...
            int[] arr = new int[20];
    
            arr[0] = 1;
            arr[1] = 1;
    
            for (int i = 2; i < arr.length; i++) {
                arr[i] = arr[i - 1] + arr[i - 2];
            }
            System.out.println(arr[19]);
            System.out.println(f(20));
        }
    
        /*
            递归解决问题,首先就是要定义一个方法:
                定义一个方法f(n):表示第n个月的兔子对数
                那么,第n-1个月的兔子对数该如何表示呢?f(n-1)
                同理,第n-2个月的兔子对数该如何表示呢?f(n-2)
    
            StackOverflowError:当堆栈溢出发生时抛出一个应用程序递归太深
         */
        public static int f(int n) {
            if(n==1 || n==2) {
                return 1;
            } else {
                return f(n - 1) + f(n - 2);
            }
        }
    }
    
  • 递归的注意事项

    • 递归一定要有出口。否则内存溢出
    • 递归虽然有出口,但是递归的次数也不宜过多。否则内存溢出

2.2递归求阶乘【应用】

  • 案例需求

    ​ 用递归求5的阶乘,并把结果在控制台输出

  • 代码实现

    public class DiGuiDemo01 {
        public static void main(String[] args) {
            //调用方法
            int result = jc(5);
            //输出结果
            System.out.println("5的阶乘是:" + result);
        }
    
        //定义一个方法,用于递归求阶乘,参数为一个int类型的变量
        public static int jc(int n) {
            //在方法内部判断该变量的值是否是1
            if(n == 1) {
                //是:返回1
                return 1;
            } else {
                //不是:返回n*(n-1)!
                return n*jc(n-1);
            }
        }
    }
    

2.3递归遍历目录【应用】

  • 案例需求

    ​ 给定一个路径(E:\itcast),通过递归完成遍历该目录下所有内容,并把所有文件的绝对路径输出在控制台

  • 代码实现

    public class DiGuiDemo02 {
        public static void main(String[] args) {
            //根据给定的路径创建一个File对象
    //        File srcFile = new File("E:\\itcast");
            File srcFile = new File("E:\\itheima");
    
            //调用方法
            getAllFilePath(srcFile);
        }
    
        //定义一个方法,用于获取给定目录下的所有内容,参数为第1步创建的File对象
        public static void getAllFilePath(File srcFile) {
            //获取给定的File目录下所有的文件或者目录的File数组
            File[] fileArray = srcFile.listFiles();
            //遍历该File数组,得到每一个File对象
            if(fileArray != null) {
                for(File file : fileArray) {
                    //判断该File对象是否是目录
                    if(file.isDirectory()) {
                        //是:递归调用
                        getAllFilePath(file);
                    } else {
                        //不是:获取绝对路径输出在控制台
                        System.out.println(file.getAbsolutePath());
                    }
                }
            }
        }
    }
    

3.IO流

3.1 IO流概述和分类【理解】

  • IO流介绍
    • IO:输入/输出(Input/Output)
    • 流:是一种抽象概念,是对数据传输的总称。也就是说数据在设备间的传输称为流,流的本质是数据传输
    • IO流就是用来处理设备间数据传输问题的。常见的应用:文件复制;文件上传;文件下载
  • IO流的分类
    • 按照数据的流向
      • 输入流:读数据
      • 输出流:写数据
    • 按照数据类型来分
      • 字节流
        • 字节输入流
        • 字节输出流
      • 字符流
        • 字符输入流
        • 字符输出流
  • IO流的使用场景
    • 如果操作的是纯文本文件,优先使用字符流
    • 如果操作的是图片、视频、音频等二进制文件。优先使用字节流
    • 如果不确定文件类型,优先使用字节流。字节流是万能的流

3.2字节流写数据【应用】

  • 字节流抽象基类

    • InputStream:这个抽象类是表示字节输入流的所有类的超类
    • OutputStream:这个抽象类是表示字节输出流的所有类的超类
    • 子类名特点:子类名称都是以其父类名作为子类名的后缀
  • 字节输出流

    • FileOutputStream(String name):创建文件输出流以指定的名称写入文件
  • 使用字节输出流写数据的步骤

    • 创建字节输出流对象(调用系统功能创建了文件,创建字节输出流对象,让字节输出流对象指向文件)
    • 调用字节输出流对象的写数据方法
    • 释放资源(关闭此文件输出流并释放与此流相关联的任何系统资源)
  • 示例代码

    public class FileOutputStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //创建字节输出流对象
            //FileOutputStream(String name):创建文件输出流以指定的名称写入文件
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            /*
                做了三件事情:
                    A:调用系统功能创建了文件
                    B:创建了字节输出流对象
                    C:让字节输出流对象指向创建好的文件
             */
    
            //void write(int b):将指定的字节写入此文件输出流
            fos.write(97);
    //        fos.write(57);
    //        fos.write(55);
    
            //最后都要释放资源
            //void close():关闭此文件输出流并释放与此流相关联的任何系统资源。
            fos.close();
        }
    }
    

3.3字节流写数据的三种方式【应用】

  • 写数据的方法分类

    方法名说明
    void write(int b)将指定的字节写入此文件输出流 一次写一个字节数据
    void write(byte[] b)将 b.length字节从指定的字节数组写入此文件输出流 一次写一个字节数组数据
    void write(byte[] b, int off, int len)将 len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流 一次写一个字节数组的部分数据
  • 示例代码

    public class FileOutputStreamDemo02 {
        public static void main(String[] args) throws IOException {
            //FileOutputStream(String name):创建文件输出流以指定的名称写入文件
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            //new File(name)
    //        FileOutputStream fos = new FileOutputStream(new File("myByteStream\\fos.txt"));
    
            //FileOutputStream(File file):创建文件输出流以写入由指定的 File对象表示的文件
    //        File file = new File("myByteStream\\fos.txt");
    //        FileOutputStream fos2 = new FileOutputStream(file);
    //        FileOutputStream fos2 = new FileOutputStream(new File("myByteStream\\fos.txt"));
    
            //void write(int b):将指定的字节写入此文件输出流
    //        fos.write(97);
    //        fos.write(98);
    //        fos.write(99);
    //        fos.write(100);
    //        fos.write(101);
    
    //        void write(byte[] b):将 b.length字节从指定的字节数组写入此文件输出流
    //        byte[] bys = {97, 98, 99, 100, 101};
            //byte[] getBytes():返回字符串对应的字节数组
            byte[] bys = "abcde".getBytes();
    //        fos.write(bys);
    
            //void write(byte[] b, int off, int len):将 len字节从指定的字节数组开始,从偏移量off开始写入此文件输出流
    //        fos.write(bys,0,bys.length);
            fos.write(bys,1,3);
    
            //释放资源
            fos.close();
        }
    }
    

3.4字节流写数据的两个小问题【应用】

  • 字节流写数据如何实现换行

    • windows:\r\n
    • linux:\n
    • mac:\r
  • 字节流写数据如何实现追加写入

    • public FileOutputStream(String name,boolean append)
    • 创建文件输出流以指定的名称写入文件。如果第二个参数为true ,则字节将写入文件的末尾而不是开头
  • 示例代码

    public class FileOutputStreamDemo03 {
        public static void main(String[] args) throws IOException {
            //创建字节输出流对象
    //        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
            FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt",true);
    
            //写数据
            for (int i = 0; i < 10; i++) {
                fos.write("hello".getBytes());
                fos.write("\r\n".getBytes());
            }
    
            //释放资源
            fos.close();
        }
    }
    

3.5字节流写数据加异常处理【应用】

  • 异常处理格式

    • try-catch-finally

      try{
      	可能出现异常的代码;
      }catch(异常类名 变量名){
      	异常的处理代码;
      }finally{
      	执行所有清除操作;
      }
      
    • finally特点

      • 被finally控制的语句一定会执行,除非JVM退出
  • 示例代码

    public class FileOutputStreamDemo04 {
        public static void main(String[] args) {
            //加入finally来实现释放资源
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream("myByteStream\\fos.txt");
                fos.write("hello".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

3.6字节流读数据(一次读一个字节数据)【应用】

  • 字节输入流

    • FileInputStream(String name):通过打开与实际文件的连接来创建一个FileInputStream ,该文件由文件系统中的路径名name命名
  • 字节输入流读取数据的步骤

    • 创建字节输入流对象
    • 调用字节输入流对象的读数据方法
    • 释放资源
  • 示例代码

    public class FileInputStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //创建字节输入流对象
            //FileInputStream(String name)
            FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
    
            int by;
            /*
                fis.read():读数据
                by=fis.read():把读取到的数据赋值给by
                by != -1:判断读取到的数据是否是-1
             */
            while ((by=fis.read())!=-1) {
                System.out.print((char)by);
            }
    
            //释放资源
            fis.close();
        }
    }
    

3.7字节流复制文本文件【应用】

  • 案例需求

    ​ 把“E:\itcast\窗里窗外.txt”复制到模块目录下的“窗里窗外.txt”

  • 实现步骤

    • 复制文本文件,其实就把文本文件的内容从一个文件中读取出来(数据源),然后写入到另一个文件中(目的地)

    • 数据源:

      ​ E:\itcast\窗里窗外.txt — 读数据 — InputStream — FileInputStream

    • 目的地:

      ​ myByteStream\窗里窗外.txt — 写数据 — OutputStream — FileOutputStream

  • 代码实现

    public class CopyTxtDemo {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字节输入流对象
            FileInputStream fis = new FileInputStream("E:\\itcast\\窗里窗外.txt");
            //根据目的地创建字节输出流对象
            FileOutputStream fos = new FileOutputStream("myByteStream\\窗里窗外.txt");
    
            //读写数据,复制文本文件(一次读取一个字节,一次写入一个字节)
            int by;
            while ((by=fis.read())!=-1) {
                fos.write(by);
            }
    
            //释放资源
            fos.close();
            fis.close();
        }
    }
    

3.8字节流读数据(一次读一个字节数组数据)【应用】

  • 一次读一个字节数组的方法

    • public int read(byte[] b):从输入流读取最多b.length个字节的数据
    • 返回的是读入缓冲区的总字节数,也就是实际的读取字节个数
  • 示例代码

    public class FileInputStreamDemo02 {
        public static void main(String[] args) throws IOException {
            //创建字节输入流对象
            FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
    
            /*
                hello\r\n
                world\r\n
    
                第一次:hello
                第二次:\r\nwor
                第三次:ld\r\nr
    
             */
    
            byte[] bys = new byte[1024]; //1024及其整数倍
            int len;
            while ((len=fis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //释放资源
            fis.close();
        }
    }
    

3.9字节流复制图片【应用】

  • 案例需求

    ​ 把“E:\itcast\mn.jpg”复制到模块目录下的“mn.jpg”

  • 实现步骤

    • 根据数据源创建字节输入流对象
    • 根据目的地创建字节输出流对象
    • 读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
    • 释放资源
  • 代码实现

    public class CopyJpgDemo {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字节输入流对象
            FileInputStream fis = new FileInputStream("E:\\itcast\\mn.jpg");
            //根据目的地创建字节输出流对象
            FileOutputStream fos = new FileOutputStream("myByteStream\\mn.jpg");
    
            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            byte[] bys = new byte[1024];
            int len;
            while ((len=fis.read(bys))!=-1) {
                fos.write(bys,0,len);
            }
    
            //释放资源
            fos.close();
            fis.close();
        }
    }
    

0

1.字节缓冲流(没看)

1.1字节缓冲流构造方法【应用】

  • 字节缓冲流介绍

    • lBufferOutputStream:该类实现缓冲输出流。 通过设置这样的输出流,应用程序可以向底层输出流写入字节,而不必为写入的每个字节导致底层系统的调用

    • lBufferedInputStream:创建BufferedInputStream将创建一个内部缓冲区数组。 当从流中读取或跳过字节时,内部缓冲区将根据需要从所包含的输入流中重新填充,一次很多字节

  • 构造方法:

    方法名说明
    BufferedOutputStream(OutputStream out)创建字节缓冲输出流对象
    BufferedInputStream(InputStream in)创建字节缓冲输入流对象
  • 示例代码

    public class BufferStreamDemo {
        public static void main(String[] args) throws IOException {
            //字节缓冲输出流:BufferedOutputStream(OutputStream out)
     
            BufferedOutputStream bos = new BufferedOutputStream(new 				                                       FileOutputStream("myByteStream\\bos.txt"));
            //写数据
            bos.write("hello\r\n".getBytes());
            bos.write("world\r\n".getBytes());
            //释放资源
            bos.close();
        
    
            //字节缓冲输入流:BufferedInputStream(InputStream in)
            BufferedInputStream bis = new BufferedInputStream(new                                                          FileInputStream("myByteStream\\bos.txt"));
    
            //一次读取一个字节数据
    //        int by;
    //        while ((by=bis.read())!=-1) {
    //            System.out.print((char)by);
    //        }
    
            //一次读取一个字节数组数据
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //释放资源
            bis.close();
        }
    }
    

1.2字节流复制视频【应用】

  • 案例需求

    把“E:\itcast\字节流复制图片.avi”复制到模块目录下的“字节流复制图片.avi”

  • 实现步骤

    • 根据数据源创建字节输入流对象

    • 根据目的地创建字节输出流对象

    • 读写数据,复制视频

    • 释放资源

  • 代码实现

    public class CopyAviDemo {
        public static void main(String[] args) throws IOException {
            //记录开始时间
            long startTime = System.currentTimeMillis();
    
            //复制视频
    //        method1();
    //        method2();
    //        method3();
            method4();
    
            //记录结束时间
            long endTime = System.currentTimeMillis();
            System.out.println("共耗时:" + (endTime - startTime) + "毫秒");
        }
    
        //字节缓冲流一次读写一个字节数组
        public static void method4() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\字节流复制图片.avi"));
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                bos.write(bys,0,len);
            }
    
            bos.close();
            bis.close();
        }
    
        //字节缓冲流一次读写一个字节
        public static void method3() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\字节流复制图片.avi"));
    
            int by;
            while ((by=bis.read())!=-1) {
                bos.write(by);
            }
    
            bos.close();
            bis.close();
        }
    
    
        //基本字节流一次读写一个字节数组
        public static void method2() throws IOException {
            //E:\\itcast\\字节流复制图片.avi
            //模块目录下的 字节流复制图片.avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\字节流复制图片.avi");
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=fis.read(bys))!=-1) {
                fos.write(bys,0,len);
            }
    
            fos.close();
            fis.close();
        }
    
        //基本字节流一次读写一个字节
        public static void method1() throws IOException {
            //E:\\itcast\\字节流复制图片.avi
            //模块目录下的 字节流复制图片.avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\字节流复制图片.avi");
    
            int by;
            while ((by=fis.read())!=-1) {
                fos.write(by);
            }
    
            fos.close();
            fis.close();
        }
    }
    

2.字符流

2.1为什么会出现字符流【理解】

  • 字符流的介绍

    由于字节流操作中文不是特别的方便,所以Java就提供字符流

    字符流 = 字节流 + 编码表

  • 中文的字节存储方式

    用字节流复制文本文件时,文本文件也会有中文,但是没有问题,原因是最终底层操作会自动进行字节拼接成中文,如何识别是中文的呢?

    汉字在存储的时候,无论选择哪种编码存储,第一个字节都是负数

2.2编码表【理解】

  • 什么是字符集

    是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等

    l计算机要准确的存储和识别各种字符集符号,就需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBXXX字符集、Unicode字符集等

  • 常见的字符集

    • ASCII字符集:

      lASCII:是基于拉丁字母的一套电脑编码系统,用于显示现代英语,主要包括控制字符(回车键、退格、换行键等)和可显示字符(英文大小写字符、阿拉伯数字和西文符号)

      基本的ASCII字符集,使用7位表示一个字符,共128字符。ASCII的扩展字符集使用8位表示一个字符,共256字符,方便支持欧洲常用字符。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等

    • GBXXX字符集:

      GBK:最常用的中文码表。是在GB2312标准基础上的扩展规范,使用了双字节编码方案,共收录了21003个汉字,完全兼容GB2312标准,同时支持繁体汉字以及日韩汉字等

    • Unicode字符集:

      UTF-8编码:可以用来表示Unicode标准中任意字符,它是电子邮件、网页及其他存储或传送文字的应用 中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。它使用一至四个字节为每个字符编码

      编码规则:

      128个US-ASCII字符,只需一个字节编码

      拉丁文等字符,需要二个字节编码

      大部分常用字(含中文),使用三个字节编码

      其他极少使用的Unicode辅助字符,使用四字节编码

2.3字符串中的编码解码问题【应用】

  • 相关方法

    方法名说明
    byte[] getBytes()使用平台的默认字符集将该 String编码为一系列字节
    byte[] getBytes(String charsetName)使用指定的字符集将该 String编码为一系列字节
    String(byte[] bytes)使用平台的默认字符集解码指定的字节数组来创建字符串
    String(byte[] bytes, String charsetName)通过指定的字符集解码指定的字节数组来创建字符串
  • 代码演示

    public class StringDemo {
        public static void main(String[] args) throws UnsupportedEncodingException {
            //定义一个字符串
            String s = "中国";
    
            //byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67]
            //byte[] bys = s.getBytes("UTF-8"); //[-28, -72, -83, -27, -101, -67]
            byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
            System.out.println(Arrays.toString(bys));
    
            //String ss = new String(bys);
            //String ss = new String(bys,"UTF-8");
            String ss = new String(bys,"GBK");
            System.out.println(ss);
        }
    }
    

2.4字符流中的编码解码问题【应用】

  • 字符流中和编码解码问题相关的两个类

    • InputStreamReader:是从字节流到字符流的桥梁

      ​ 它读取字节,并使用指定的编码将其解码为字符

      ​ 它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

    • OutputStreamWriter:是从字符流到字节流的桥梁

      ​ 是从字符流到字节流的桥梁,使用指定的编码将写入的字符编码为字节

      ​ 它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

  • 构造方法

    方法名说明
    InputStreamReader(InputStream in)使用默认字符编码创建InputStreamReader对象
    InputStreamReader(InputStream in,String chatset)使用指定的字符编码创建InputStreamReader对象
    OutputStreamWriter(OutputStream out)使用默认字符编码创建OutputStreamWriter对象
    OutputStreamWriter(OutputStream out,String charset)使用指定的字符编码创建OutputStreamWriter对象
  • 代码演示

    public class ConversionStreamDemo {
        public static void main(String[] args) throws IOException {
            //OutputStreamWriter osw = new OutputStreamWriter(new                                             FileOutputStream("myCharStream\\osw.txt"));
            OutputStreamWriter osw = new OutputStreamWriter(new                                              FileOutputStream("myCharStream\\osw.txt"),"GBK");
            osw.write("中国");
            osw.close();
    
            //InputStreamReader isr = new InputStreamReader(new 	                                         FileInputStream("myCharStream\\osw.txt"));
            InputStreamReader isr = new InputStreamReader(new                                                 FileInputStream("myCharStream\\osw.txt"),"GBK");
            //一次读取一个字符数据
            int ch;
            while ((ch=isr.read())!=-1) {
                System.out.print((char)ch);
            }
            isr.close();
        }
    }
    

2.5字符流写数据的5种方式【应用】

  • 方法介绍

    方法名说明
    void write(int c)写一个字符
    void write(char[] cbuf)写入一个字符数组
    void write(char[] cbuf, int off, int len)写入字符数组的一部分
    void write(String str)写一个字符串
    void write(String str, int off, int len)写一个字符串的一部分
  • 刷新和关闭的方法

    方法名说明
    flush()刷新流,之后还可以继续写数据
    close()关闭流,释放资源,但是在关闭之前会先刷新流。一旦关闭,就不能再写数据
  • 代码演示

    public class OutputStreamWriterDemo {
        public static void main(String[] args) throws IOException {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\osw.txt"));
    
            //void write(int c):写一个字符
    //        osw.write(97);
    //        osw.write(98);
    //        osw.write(99);
    
            //void writ(char[] cbuf):写入一个字符数组
            char[] chs = {'a', 'b', 'c', 'd', 'e'};
    //        osw.write(chs);
    
            //void write(char[] cbuf, int off, int len):写入字符数组的一部分
    //        osw.write(chs, 0, chs.length);
    //        osw.write(chs, 1, 3);
    
            //void write(String str):写一个字符串
    //        osw.write("abcde");
    
            //void write(String str, int off, int len):写一个字符串的一部分
    //        osw.write("abcde", 0, "abcde".length());
            osw.write("abcde", 1, 3);
    
            //释放资源
            osw.close();
        }
    }
    

2.6字符流读数据的2种方式【应用】

  • 方法介绍

    方法名说明
    int read()一次读一个字符数据
    int read(char[] cbuf)一次读一个字符数组数据
  • 代码演示

    public class InputStreamReaderDemo {
        public static void main(String[] args) throws IOException {
       
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
    
            //int read():一次读一个字符数据
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            System.out.print((char)ch);
    //        }
    
            //int read(char[] cbuf):一次读一个字符数组数据
            char[] chs = new char[1024];
            int len;
            while ((len = isr.read(chs)) != -1) {
                System.out.print(new String(chs, 0, len));
            }
    
            //释放资源
            isr.close();
        }
    }
    

2.7字符流复制Java文件【应用】

  • 案例需求

    把模块目录下的“ConversionStreamDemo.java” 复制到模块目录下的“Copy.java”

  • 实现步骤

    • 根据数据源创建字符输入流对象
    • 根据目的地创建字符输出流对象
    • 读写数据,复制文件
    • 释放资源
  • 代码实现

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字符输入流对象
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
            //根据目的地创建字符输出流对象
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\Copy.java"));
    
            //读写数据,复制文件
            //一次读写一个字符数据
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            osw.write(ch);
    //        }
    
            //一次读写一个字符数组数据
            char[] chs = new char[1024];
            int len;
            while ((len=isr.read(chs))!=-1) {
                osw.write(chs,0,len);
            }
    
            //释放资源
            osw.close();
            isr.close();
        }
    }
    

2.8字符流复制Java文件改进版【应用】

  • 案例需求

    使用便捷流对象,把模块目录下的“ConversionStreamDemo.java” 复制到模块目录下的“Copy.java”

  • 实现步骤

    • 根据数据源创建字符输入流对象

    • 根据目的地创建字符输出流对象

    • 读写数据,复制文件

    • 释放资源

  • 代码实现

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字符输入流对象
            FileReader fr = new FileReader("myCharStream\\ConversionStreamDemo.java");
            //根据目的地创建字符输出流对象
            FileWriter fw = new FileWriter("myCharStream\\Copy.java");
    
            //读写数据,复制文件
    //        int ch;
    //        while ((ch=fr.read())!=-1) {
    //            fw.write(ch);
    //        }
    
            char[] chs = new char[1024];
            int len;
            while ((len=fr.read(chs))!=-1) {
                fw.write(chs,0,len);
            }
    
            //释放资源
            fw.close();
            fr.close();
        }
    }
    

2.9字符缓冲流【应用】(没看)

  • 字符缓冲流介绍

    • BufferedWriter:将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入,可以指定缓冲区大小,或者可以接受默认大小。默认值足够大,可用于大多数用途

    • BufferedReader:从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取,可以指定缓冲区大小,或者可以使用默认大小。 默认值足够大,可用于大多数用途

  • 构造方法

    方法名说明
    BufferedWriter(Writer out)创建字符缓冲输出流对象
    BufferedReader(Reader in)创建字符缓冲输入流对象
  • 代码演示

    public class BufferedStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //BufferedWriter(Writer out)
            BufferedWriter bw = new BufferedWriter(new                                                            FileWriter("myCharStream\\bw.txt"));
            bw.write("hello\r\n");
            bw.write("world\r\n");
            bw.close();
    
            //BufferedReader(Reader in)
            BufferedReader br = new BufferedReader(new                                                           FileReader("myCharStream\\bw.txt"));
    
            //一次读取一个字符数据
    //        int ch;
    //        while ((ch=br.read())!=-1) {
    //            System.out.print((char)ch);
    //        }
    
            //一次读取一个字符数组数据
            char[] chs = new char[1024];
            int len;
            while ((len=br.read(chs))!=-1) {
                System.out.print(new String(chs,0,len));
            }
    
            br.close();
        }
    }
    

2.10字符缓冲流复制Java文件【应用】

  • 案例需求

    把模块目录下的ConversionStreamDemo.java 复制到模块目录下的 Copy.java

  • 实现步骤

    • 根据数据源创建字符缓冲输入流对象
    • 根据目的地创建字符缓冲输出流对象
    • 读写数据,复制文件,使用字符缓冲流特有功能实现
    • 释放资源
  • 代码实现

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //根据目的地创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //读写数据,复制文件
            //一次读写一个字符数据
    //        int ch;
    //        while ((ch=br.read())!=-1) {
    //            bw.write(ch);
    //        }
    
            //一次读写一个字符数组数据
            char[] chs = new char[1024];
            int len;
            while ((len=br.read(chs))!=-1) {
                bw.write(chs,0,len);
            }
    
            //释放资源
            bw.close();
            br.close();
        }
    }
    

2.11字符缓冲流特有功能【应用】

  • 方法介绍

    BufferedWriter:

    方法名说明
    void newLine()写一行行分隔符,行分隔符字符串由系统属性定义

    BufferedReader:

    方法名说明
    String readLine()读一行文字。 结果包含行的内容的字符串,不包括任何行终止字符如果流的结尾已经到达,则为null
  • 代码演示

    public class BufferedStreamDemo02 {
        public static void main(String[] args) throws IOException {
    
            //创建字符缓冲输出流
            BufferedWriter bw = new BufferedWriter(new                                                          FileWriter("myCharStream\\bw.txt"));
    
            //写数据
            for (int i = 0; i < 10; i++) {
                bw.write("hello" + i);
                //bw.write("\r\n");
                bw.newLine();
                bw.flush();
            }
    
            //释放资源
            bw.close();
    
            //创建字符缓冲输入流
            BufferedReader br = new BufferedReader(new                                                          FileReader("myCharStream\\bw.txt"));
    
            String line;
            while ((line=br.readLine())!=null) {
                System.out.println(line);
            }
    
            br.close();
        }
    }
    

2.12字符缓冲流特有功能复制Java文件【应用】

  • 案例需求

    使用特有功能把模块目录下的ConversionStreamDemo.java 复制到模块目录下的 Copy.java

  • 实现步骤

    • 根据数据源创建字符缓冲输入流对象
    • 根据目的地创建字符缓冲输出流对象
    • 读写数据,复制文件,使用字符缓冲流特有功能实现
    • 释放资源
  • 代码实现

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //根据数据源创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //根据目的地创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //读写数据,复制文件
            //使用字符缓冲流特有功能实现
            String line;
            while ((line=br.readLine())!=null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
    
            //释放资源
            bw.close();
            br.close();
        }
    }
    

2.13IO流小结【理解】

  • 字节流

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tBGT7K4B-1627200757954)(img\IO小结字节流.jpg)]

  • 字符流

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BPzLiuvs-1627200757958)(img\IO小结字符流.jpg)]

3练习案例

3.1集合到文件【应用】

  • 案例需求

    把文本文件中的数据读取到集合中,并遍历集合。要求:文件中每一行数据是一个集合元素

  • 实现步骤

    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据存储到集合中
    • 释放资源
    • 遍历集合
  • 代码实现

    public class TxtToArrayListDemo {
        public static void main(String[] args) throws IOException {
            //创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\array.txt"));
    
            //创建ArrayList集合对象
            ArrayList<String> array = new ArrayList<String>();
    
            //调用字符缓冲输入流对象的方法读数据
            String line;
            while ((line=br.readLine())!=null) {
                //把读取到的字符串数据存储到集合中
                array.add(line);
            }
            //释放资源
            br.close();
            //遍历集合
            for(String s : array) {
                System.out.println(s);
            }
        }
    }
    

3.2文件到集合【应用】

  • 案例需求

    把ArrayList集合中的字符串数据写入到文本文件。要求:每一个字符串元素作为文件中的一行数据

  • 实现步骤

    • 创建ArrayList集合
    • 往集合中存储字符串元素
    • 创建字符缓冲输出流对象
    • 遍历集合,得到每一个字符串数据
    • 调用字符缓冲输出流对象的方法写数据
    • 释放资源
  • 代码实现

    public class ArrayListToTxtDemo {
        public static void main(String[] args) throws IOException {
            //创建ArrayList集合
            ArrayList<String> array = new ArrayList<String>();
    
            //往集合中存储字符串元素
            array.add("hello");
            array.add("world");
            array.add("java");
    
            //创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\array.txt"));
    
            //遍历集合,得到每一个字符串数据
            for(String s : array) {
                //调用字符缓冲输出流对象的方法写数据
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
    
            //释放资源
            bw.close();
        }
    }
    

3.3点名器【应用】

  • 案例需求

    我有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随点名器

  • 实现步骤

    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据存储到集合中
    • 释放资源
    • 使用Random产生一个随机数,随机数的范围在:[0,集合的长度)
    • 把第6步产生的随机数作为索引到ArrayList集合中获取值
    • 把第7步得到的数据输出在控制台
  • 代码实现

    public class CallNameDemo {
        public static void main(String[] args) throws IOException {
            //创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\names.txt"));
    
            //创建ArrayList集合对象
            ArrayList<String> array = new ArrayList<String>();
    
            //调用字符缓冲输入流对象的方法读数据
            String line;
            while ((line=br.readLine())!=null) {
                //把读取到的字符串数据存储到集合中
                array.add(line);
            }
    
            //释放资源
            br.close();
    
            //使用Random产生一个随机数,随机数的范围在:[0,集合的长度)
            Random r = new Random();
            int index = r.nextInt(array.size());
    
            //把第6步产生的随机数作为索引到ArrayList集合中获取值
            String name = array.get(index);
    
            //把第7步得到的数据输出在控制台
            System.out.println("幸运者是:" + name);
        }
    }
    

3.4集合到文件改进版【应用】

  • 案例需求

    把ArrayList集合中的学生数据写入到文本文件。要求:每一个学生对象的数据作为文件中的一行数据
    ​ 格式:学号,姓名,年龄,居住地 举例:itheima001,林青霞,30,西安

  • 实现步骤

    • 定义学生类
    • 创建ArrayList集合
    • 创建学生对象
    • 把学生对象添加到集合中
    • 创建字符缓冲输出流对象
    • 遍历集合,得到每一个学生对象
    • 把学生对象的数据拼接成指定格式的字符串
    • 调用字符缓冲输出流对象的方法写数据
    • 释放资源
  • 代码实现

    • 学生类

      public class Student {
          private String sid;
          private String name;
          private int age;
          private String address;
      
          public Student() {
          }
      
          public Student(String sid, String name, int age, String address) {
              this.sid = sid;
              this.name = name;
              this.age = age;
              this.address = address;
          }
      
          public String getSid() {
              return sid;
          }
      
          public void setSid(String sid) {
              this.sid = sid;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String getAddress() {
              return address;
          }
      
          public void setAddress(String address) {
              this.address = address;
          }
      }
      
    • 测试类

      public class ArrayListToFileDemo {
          public static void main(String[] args) throws IOException {
              //创建ArrayList集合
              ArrayList<Student> array = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("itheima001", "林青霞", 30, "西安");
              Student s2 = new Student("itheima002", "张曼玉", 35, "武汉");
              Student s3 = new Student("itheima003", "王祖贤", 33, "郑州");
      
              //把学生对象添加到集合中
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //创建字符缓冲输出流对象
              BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\students.txt"));
      
              //遍历集合,得到每一个学生对象
              for (Student s : array) {
                  //把学生对象的数据拼接成指定格式的字符串
                  StringBuilder sb = new StringBuilder();
                  sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
      
                  //调用字符缓冲输出流对象的方法写数据
                  bw.write(sb.toString());
                  bw.newLine();
                  bw.flush();
              }
      
              //释放资源
              bw.close();
          }
      }
      

3.5文件到集合改进版【应用】

  • 案例需求

    把文本文件中的数据读取到集合中,并遍历集合。要求:文件中每一行数据是一个学生对象的成员变量值
    举例:itheima001,林青霞,30,西安

  • 实现步骤

    • 定义学生类
    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据用split()进行分割,得到一个字符串数组
    • 创建学生对象
    • 把字符串数组中的每一个元素取出来对应的赋值给学生对象的成员变量值
    • 把学生对象添加到集合
    • 释放资源
    • 遍历集合
  • 代码实现

    • 学生类

      ​ 同上

    • 测试类

      public class FileToArrayListDemo {
          public static void main(String[] args) throws IOException {
              //创建字符缓冲输入流对象
              BufferedReader br = new BufferedReader(new FileReader("myCharStream\\students.txt"));
      
              //创建ArrayList集合对象
              ArrayList<Student> array = new ArrayList<Student>();
      
              //调用字符缓冲输入流对象的方法读数据
              String line;
              while ((line = br.readLine()) != null) {
                  //把读取到的字符串数据用split()进行分割,得到一个字符串数组
                  String[] strArray = line.split(",");
      
                  //创建学生对象
                  Student s = new Student();
                  //把字符串数组中的每一个元素取出来对应的赋值给学生对象的成员变量值
                  //itheima001,林青霞,30,西安
                  s.setSid(strArray[0]);
                  s.setName(strArray[1]);
                  s.setAge(Integer.parseInt(strArray[2]));
                  s.setAddress(strArray[3]);
      
                  //把学生对象添加到集合
                  array.add(s);
              }
      
              //释放资源
              br.close();
      
              //遍历集合
              for (Student s : array) {
                  System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
              }
          }
      }
      

请添加图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值