Java第十六天~第十七天/11.18~11.19

来源:互联网 发布:淘宝话费充值 编辑:程序博客网 时间:2024/05/16 10:40

day16

一、Map集合

Map集合是双列集合,用来存储有键值对 对应关系的数据,且Map集合是一个接口 * Map集合的数据结构只跟键有关(键唯一),和值没有关系 * 子实现类: *   HashMap:底层数据结构是哈希表    允许插入null键和null值 *        特点:元素无序,但唯一  唯一是重写了hashCode()和equal()方法 *          方法:对象调用 *             put(key,value):添加元素 第一次添加返回null 再次添加就会返回上一     次的值 键相同,值覆盖 *             size():获取集合的长度 *             isEmpty():判断集合是否为空,返回Boolean类型 *             containsKey(key):判断集合有没有这个键 *             containsValue(value):判断集合有没有这个值 *             get(key):根据键获取对应的值 *           遍历:  *             keySet():获取结合所有的键的集合 *             entrySet():获取所有键值对 的集合 *                   Entry<Object,Object> 两个方法 getKey()和getValue() *             values():获取所有的值 *             clear():清除所有的元素 *             remove(key):根据键移除这一对键值对 *   Hashtable (开发人员疏忽,此处应该驼峰命名,T大写) *        特点:与HashMap特点一致。 *   两者区别: *        HashMap非同步,不安全,但执行效率高 *        Hashtable同步,安全,但执行效率低                    *   LinkedHashMap:底层数据结构是链表和哈希表  *                 链表结构保证有序(该有序指存储元素和取出元素顺序一致), *                 哈希表结构保证元素唯一 *                 底层也是重写了hashCode()和equal()方法来保证唯一 *            Map接口的哈希表和链接列表实现形式,具有可预知的迭代顺序 *   TreeMap:底层数据结构是红黑树(二叉树) 不允许插入null键,但当键不是null时,可以插入null值 *            能够对元素进行排序  自然排序和比较器排序。但必须实现Comparable<T>接口,重写compareTo()方法   *            元素的顺序 就是根据compareTo方法返回的值来确定排序 *            自定义对象时,要重写hashCode()和equal()方法,Integer类型和String类型默认重写  *   自然排序: *       在对象类中实现Comparable接口,并且要重写compareTo()方法 *   比较器排序: *       不在对象类中实现Comparable接口,在测试类中使用匿名内部类形式       

1、Map集合

package org.westos_Map;import java.util.HashMap;public class MapDemo {    public static void main(String[] args) {        HashMap<String, String> hm = new HashMap<>();        String str = hm.put("武大", "金莲");        String str2 = hm.put("武大", "烧饼");        hm.put("邓超", "sunli");        hm.put("wenzhang", "mayili");        System.out.println(str);        System.out.println(str2);        System.out.println(hm);//没有打印地址,说明底层重写了toString()方法        /*null        金莲        {wenzhang=mayili, 武大=烧饼, 邓超=sunli}*/        String remove = hm.remove("邓超");        System.out.println(remove);//sunli        System.out.println(hm);//{wenzhang=mayili, 武大=烧饼}        System.out.println(hm.keySet());//[wenzhang, 武大]        System.out.println(hm.values());//[mayili, 烧饼]        System.out.println(hm.size());//2    }}

2、HashMap集合基本数据类型的存储

package org.westos_Map;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;public class HashMapDemo {    public static void main(String[] args) {        HashMap<String, Student> hm = new HashMap<String, Student>();        hm.put("001", new Student("貂蝉",21));        hm.put("001", new Student("貂蝉",21));        hm.put("002", new Student("王昭君",22));        hm.put("003", new Student("西施",23));        hm.put("004", new Student("杨玉环",24));        //遍历集合        //方式一:keySet()        Set<String> keySet = hm.keySet();        for(String key:keySet){            System.out.println(key+"---"+hm.get(key));            /*004---Student [name=杨玉环, age=24]            001---Student [name=貂蝉, age=21]            002---Student [name=王昭君, age=22]            003---Student [name=西施, age=23]*/        }        System.out.println("-------------------");        //方式二:entrySet()        Set<Entry<String,Student>> entrySet = hm.entrySet();        for(Entry<String,Student> en:entrySet){            System.out.println(en.getKey()+"---"+en.getValue());            /*004---Student [name=杨玉环, age=24]            001---Student [name=貂蝉, age=21]            002---Student [name=王昭君, age=22]            003---Student [name=西施, age=23]*/        }    }}

3、HashMap集合自定义类型的存储

package org.westos_Map;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;public class HashMapDemo2 {    public static void main(String[] args) {        HashMap<Student, String> hm = new HashMap<Student,String>();        //此时要在自定义类中重写hashCode()和equal()方法        hm.put(new Student("貂蝉",20), "001");        hm.put(new Student("貂蝉",20), "001");        hm.put(new Student("王昭君",21), "002");        hm.put(new Student("西施",22), "003");        hm.put(new Student("杨玉环",23), "004");        //遍历        //方式一        Set<Entry<Student,String>> entrySet = hm.entrySet();        for(Entry<Student,String> en:entrySet){            System.out.println(en.getKey()+"---"+en.getValue());            /*             * Student [name=杨玉环, age=23]---004              * Student [name=王昭君, age=21]---002             * Student [name=西施, age=22]---003              * Student [name=貂蝉, age=20]---001             */        }    }}

4、LinkedHashMap集合基本数据类型的存储

package org.westos_Map;import java.util.LinkedHashMap;import java.util.Set;public class LinkedHashMapDemo {    public static void main(String[] args) {        LinkedHashMap<Integer,String> link = new LinkedHashMap<Integer,String>();        link.put(1, "张三");        link.put(2, "李四");        link.put(3, "王五");        link.put(0, "狗剩");        link.put(1, "张三");        link.put(4, "王麻子");        link.put(5, "狗蛋");        Set<Integer> keySet = link.keySet();        for(Integer key:keySet){            System.out.println(key+"---"+link.get(key));            /*1---张三              2---李四              3---王五              0---狗剩              4---王麻子              5---狗蛋*/      }    }}

5、LinkedHashMap集合存储自定义类型

package org.westos_Map;import java.util.LinkedHashMap;import java.util.Map.Entry;import java.util.Set;public class LinkedHashMapDemo2 {    public static void main(String[] args) {        LinkedHashMap<Student, String> link = new LinkedHashMap<Student,String>();        link.put(new Student("张三",20), "s001");        link.put(new Student("李四",21), "s002");        link.put(new Student("王五",22), "s003");        link.put(new Student("张三",20), "s001");        link.put(new Student("王麻子",26), "s004");        link.put(new Student("韩七",25), "s008");        link.put(new Student("赵六",20), "s006");        Set<Entry<Student,String>> entrySet = link.entrySet();        for(Entry<Student,String> en:entrySet){            System.out.println(en.getKey()+"---"+en.getValue());        }    }}package org.westos_Map;public class Student {    private String name;    private int age;    public Student() {        super();    }    public Student(String name, int age) {        super();        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 String toString() {        return "Student [name=" + name + ", age=" + age + "]";    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Student other = (Student) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }}

6、TreeMap集合存储基本数据类型

package org.westos_Map;import java.util.Map.Entry;import java.util.Set;import java.util.TreeMap;public class TreeMapDemo2 {    public static void main(String[] args) {        TreeMap<Integer,String> treeMap = new TreeMap<Integer,String>();        treeMap.put(3, "二哈");        treeMap.put(1, "金毛");        treeMap.put(4, "泰迪");        treeMap.put(2, "柴犬");        treeMap.put(0, "狗剩");        Set<Entry<Integer, String>> entrySet = treeMap.entrySet();        for(Entry<Integer, String> en:entrySet){            System.out.println(en.getKey()+"---"+en.getValue());            /*默认重写了hashCode()和equal()方法            0---狗剩            1---金毛            2---柴犬            3---二哈            4---泰迪*/        }    }}

7、TreeMap集合存储自定义类型及自然排序

package org.westos_Map;import java.util.Map.Entry;import java.util.Set;import java.util.TreeMap;/** * 自定义对象及自然排序 *    自然排序:在对象类中实现Comparable接口和重写compareTo()方法 * @author 小鑫 * */public class TreeMapDemo3 {    public static void main(String[] args) {        TreeMap<Student1,String> treeMap = new TreeMap<Student1,String>();        treeMap.put(new Student1("貂蝉",21), "s1001");        treeMap.put(new Student1("王昭君",22), "s1002");        treeMap.put(new Student1("西施",23), "s1003");        treeMap.put(new Student1("杨玉环",24), "s1004");        treeMap.put(new Student1("貂蝉",21), "s1001");        treeMap.put(new Student1("高圆圆",25), "s1005");        Set<Entry<Student1, String>> entrySet = treeMap.entrySet();        for(Entry<Student1, String> en:entrySet){            System.out.println(en.getKey()+"---"+en.getValue());            //Student [name=貂蝉, age=21]---s1005            //当返回值为0时,只存了相同的那一个元素            //compareTo()中的逻辑代码需自己判断            //添加逻辑代码后打印结果:            /*Student [name=貂蝉, age=21]---s1001            Student [name=王昭君, age=22]---s1002            Student [name=西施, age=23]---s1003            Student [name=杨玉环, age=24]---s1004            Student [name=高圆圆, age=25]---s1005*/        }    }}package org.westos_Map;import java.io.Serializable;public class Student1 implements Serializable ,Comparable<Student1>{    /**     *      */    private static final long serialVersionUID = 1L;    private String name;    private int age;    public Student1() {        super();    }    public Student1(String name, int age) {        super();        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 String toString() {        return "Student [name=" + name + ", age=" + age + "]";    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Student1 other = (Student1) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }    @Override    public int compareTo(Student1 s) {        int num=this.age-s.age;        int result=num==0?this.name.compareTo(s.name):num;        return result;    }}

8、TreeMap集合存储自定义类型及比较器排序

package org.westos_Map;import java.util.Comparator;import java.util.Set;import java.util.TreeMap;/** * //比较器排序,不在对象类中实现Comparable接口和重写compareTo()方法 * @author 小鑫 * */public class TreeMapDemo4 {    public static void main(String[] args) {        TreeMap<Student2, String> treeMap = new TreeMap<Student2, String>(new Comparator<Student2>() {        //匿名内部类            @Override            public int compare(Student2 s1, Student2 s2) {                int num=s1.getAge()-s2.getAge();                int result=num==0?s1.getName().compareTo(s2.getName()):num;                return result;            }        });        treeMap.put(new Student2("貂蝉",21), "s1001");        treeMap.put(new Student2("王昭君",22), "s1002");        treeMap.put(new Student2("西施",23), "s1003");        treeMap.put(new Student2("杨玉环",24), "s1004");        treeMap.put(new Student2("貂蝉",21), "s1001");        treeMap.put(new Student2("高圆圆",25), "s1005");        Set<Student2> keySet = treeMap.keySet();        for(Student2 key:keySet){            System.out.println(key+"---"+treeMap.get(key));            /*Student2 [name=貂蝉, age=21]---s1001            Student2 [name=王昭君, age=22]---s1002            Student2 [name=西施, age=23]---s1003            Student2 [name=杨玉环, age=24]---s1004            Student2 [name=高圆圆, age=25]---s1005*/        }    }}package org.westos_Map;public class Student2 {    private String name;    private int age;    public Student2() {        super();        // TODO Auto-generated constructor stub    }    public Student2(String name, int age) {        super();        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 String toString() {        return "Student2 [name=" + name + ", age=" + age + "]";    }}

二、Map集合案例分析

1、用户随便输入一段字符串 统计字符串中每个字符出现的次数

package org.westos_案例;import java.util.HashMap;import java.util.Scanner;import java.util.Set;/** * 案例演示: 需求:用户随便输入一段字符串 统计字符串中每个字符出现的次数 *  "aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1) *  分析: *     1)输入字符串,转为字符数组 *     2)Map集合接受, *     3)存键 *        a-----5 *        b-----4 *        c-----3 *        d-----2 *        e-----1 *     4)转为字符数组 *     5)字符串拼接 * @author 小鑫 * */public class MapDemo {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.println("请输入一串字母");        String line = sc.nextLine();        HashMap<Character,Integer> map = new HashMap<Character,Integer>();        //将字符串转成字符数组        char[] chs = line.toCharArray();        //遍历这个数字,获得键的集合        for(char key:chs){            Integer value = map.get(key);            //如果这个键是第一次存,那么他获取出来的值是null            if(value==null){                map.put(key, 1);            }else{                value++;                map.put( key, value);//键相同,值覆盖            }        }        //此时集合已经有数据了        System.out.println("集合中存的是:"+map);        //遍历集合        Set<Character> keySet = map.keySet();        StringBuilder sb = new StringBuilder();        for(Character ch:keySet){            sb.append(ch).append("(").append(map.get(ch)).append(")");        }        System.out.println("结果是:"+sb);        /*请输入一串字母        adlahdjhadhlhl        集合中存的是:{d=3, a=3, l=3, j=1, h=4}        结果是:d(3)a(3)l(3)j(1)h(4)*/    }}

三、集合的嵌套

1、HashMap集合和HashMap集合的嵌套

package org.westos_案例;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;/** *  基础班 *    张三 ---20  *    李四 ---22 *  就业班  *    王五--- 21  *    赵六 ---23 * @author 小鑫 * */public class MapDemo2 {    public static void main(String[] args) {        //创建小集合        HashMap<String, Integer> jcMap = new HashMap<String,Integer>();        //添加元素        jcMap.put("张三", 20);        jcMap.put("李四", 22);        HashMap<String, Integer> jyMap = new HashMap<String,Integer>();        jyMap.put("王五", 21);        jyMap.put("赵六", 23);        //创建大集合        HashMap<String, HashMap<String, Integer>> bigMap= new HashMap<String,HashMap<String,Integer>>();        bigMap.put("基础班",jcMap);        bigMap.put("就业班",jyMap);        //遍历大集合        Set<String> keySet= bigMap.keySet();        for(String bigKey:keySet){            System.out.println(bigKey);            //获取每一个小集合            HashMap<String,Integer> hashMap = bigMap.get(bigKey);            //遍历小集合             Set<String> minSet = hashMap.keySet();            for(String minKey:minSet){                System.out.println("\t"+minKey+"---"+hashMap.get(minKey));                /*就业班                                            赵六---23                                            王五---21                             基础班                                            张三---20                                            李四---22*/            }        }    }}

2、大集合是HashMap集合和小集合是ArrayList集合的嵌套

package org.westos_案例;import java.util.ArrayList;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;/** * 三国演义        吕布        周瑜        笑傲江湖        令狐冲        林平之        神雕侠侣        郭靖        杨过    该小集合为单列集合,可以使用ArrayList集合和HashMap集合嵌套 * @author 小鑫 * */public class MapDemo3 {    public static void main(String[] args) {        //创建小的ArrayList集合        ArrayList<String> sgyy = new ArrayList<String>();        //添加元素        sgyy.add("吕布");        sgyy.add("周瑜");        ArrayList<String> xajh = new ArrayList<String>();        xajh.add("令狐冲");        xajh.add("林平之");        ArrayList<String> sdxl = new ArrayList<String>();        sdxl.add("郭靖");        sdxl.add("杨过");        //创建大集合        HashMap<String, ArrayList<String>> bigMap = new HashMap<String,ArrayList<String>>();        bigMap.put("三国演义", sgyy);        bigMap.put("笑傲江湖", xajh);        bigMap.put("神雕侠侣", sdxl);        //遍历大集合之keySet遍历        Set<String> keySet = bigMap.keySet();        for(String bigKey:keySet){            System.out.println(bigKey);            ArrayList<String> list = bigMap.get(bigKey);            for(String value:list){                System.out.println("\t"+value);          /*三国演义                吕布                周瑜            笑傲江湖                令狐冲                林平之            神雕侠侣                郭靖                杨过*/            }        }        //遍历大集合之entrySet遍历        Set<Entry<String,ArrayList<String>>> entrySet = bigMap.entrySet();        for(Entry<String,ArrayList<String>> en:entrySet){            String key = en.getKey();            System.out.println(key);            ArrayList<String> list = en.getValue();            for(String value:list){                System.out.println("\t"+value);          /*三国演义                吕布                周瑜            笑傲江湖                令狐冲                林平之            神雕侠侣                郭靖                杨过*/            }        }    }}

3、大集合是ArrayList集合和小集合是HashMap集合的嵌套

package org.westos_案例;import java.util.ArrayList;import java.util.HashMap;import java.util.Set;/** *  周瑜---小乔     吕布---貂蝉     郭靖---黄蓉     杨过---小龙女    令狐冲---任盈盈     林平之---岳灵珊     小集合是双列集合,用HashMap集合;大集合用ArrayList集合 * @author 小鑫 * */public class MapDemo4 {    public static void main(String[] args) {        //创建小集合        HashMap<String, String> sgyy = new HashMap<String,String>();        //添加元素        sgyy.put("周瑜", "小乔");        sgyy.put("吕布", "貂蝉");        HashMap<String, String> sdxl = new HashMap<String,String>();        sdxl.put("郭靖", "黄蓉");        sdxl.put("杨过", "小龙女");        HashMap<String, String> xajh = new HashMap<String,String>();        xajh.put("令狐冲", "任盈盈");        xajh.put("林平之", "岳灵珊");        //创建大集合        ArrayList<HashMap<String, String>> bigArray = new ArrayList<HashMap<String,String>>();        bigArray.add(sgyy);        bigArray.add(sdxl);        bigArray.add(xajh);        //遍历        for(HashMap<String, String> hm:bigArray){            //System.out.println(hm);            /*{周瑜=小乔, 吕布=貂蝉}            {郭靖=黄蓉, 杨过=小龙女}            {令狐冲=任盈盈, 林平之=岳灵珊}*/            //获取小集合的键集            Set<String> keySet = hm.keySet();            for(String key:keySet){                System.out.println(key+"---"+hm.get(key));            }            System.out.println();          /*周瑜---小乔            吕布---貂蝉            郭靖---黄蓉            杨过---小龙女            令狐冲---任盈盈            林平之---岳灵珊*/        }    }}

四、集合工具类

  • 集合工具类Collections针对的是Collection集合
  • Collections成员方法:
  • public static void sort(List list): 排序,默认按照自然顺序
  • public static int binarySearch(List
package org.westos_集合工具类;import java.util.ArrayList;import java.util.Collections;public class MapTool {    public static void main(String[] args) {        ArrayList<Integer> list = new ArrayList<Integer>();        list.add(20);        list.add(30);        list.add(40);        list.add(0);        list.add(10);        list.add(8);        list.add(20);        Collections.sort(list);        System.out.println(list);        //[0, 8, 10, 20, 20, 30, 40]        int index = Collections.binarySearch(list, 30);        //前提:存在一组按升序排序的元素        System.out.println(index);//5        //获取最大值最小值        Integer max = Collections.max(list);        Integer min = Collections.min(list);        System.out.println("最大值是:"+max);//最大值是:40        System.out.println("最小值是:"+min);//最小值是:0        //反转元素        Collections.reverse(list);        System.out.println(list);//[40, 30, 20, 20, 10, 8, 0]        //随机打乱数组        Collections.shuffle(list);        System.out.println("打乱后的元素是"+list);        //打乱后的元素是[20, 8, 10, 40, 30, 0, 20]    }}

五、斗地主案例

1、实现发牌,看牌逻辑

package org.westos_斗地主案例;import java.util.ArrayList;import java.util.Collections;/** * 1)首先构造一个牌盒 * 2)造一副扑克牌,装进牌盒 * 3)发牌:按照索引发 * 4)看牌     * @author 小鑫 * */public class PokerGame {    public static void main(String[] args) {        //先建一个牌盒        ArrayList<String> pokerBox = new ArrayList<String>();        //造一副扑克        String [] colors={"♥","♦","♠","♣"};        String [] nums={"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };        //将牌装进牌盒        for(String color:colors){            for(String num:nums){                pokerBox.add(color+num);            }        }        //添加大小王        pokerBox.add("☺");        pokerBox.add("☹");        //洗牌        Collections.shuffle(pokerBox);        Collections.shuffle(pokerBox);        Collections.shuffle(pokerBox);        //设置玩家和底牌        ArrayList<String> apple = new ArrayList<String>();        ArrayList<String> banner = new ArrayList<String>();        ArrayList<String> orange= new ArrayList<String>();        ArrayList<String> dipai= new ArrayList<String>();        /**         * 发牌:         *   一人一张,按照索引来发         *   apple:   0 3 6...  即除3余数为0的发给apple         *   banner:  1 4 7...  余数为1的发给banner         *   orange:  2 5 8...  余数为2的发给orange         *   底牌剩最后三张         */        for(int i=0;i<pokerBox.size();i++){            if(i>=pokerBox.size()-3){                dipai.add(pokerBox.get(i));            }else if(i%3==0){                apple.add(pokerBox.get(i));            }else if(i%3==1){                banner.add(pokerBox.get(i));            }else if(i%3==2){                orange.add(pokerBox.get(i));            }        }        //看牌,功能实现        lookPai("apple",apple );        lookPai("banner",banner );        lookPai("orange",orange );        lookPai("dipai",dipai );        /*        apple        ♦K ♠4 ♣7 ♦7 ♦10 ♥6 ♠6 ♠3 ♦Q ♣K ♦8 ♠8 ♣J ♦3 ♥3 ♠A ♦4         banner        ♥5 ♦A ♥4 ☹ ♠5 ♥2 ♦2 ♣5 ♥10 ♦6 ♣2 ♠10 ♦J ♦5 ♣3 ♣A ♣4         orange        ♥9 ♣Q ♣6 ♠2 ♣10 ♥Q ♣8 ♠Q ♥K ♥8 ♠K ☺ ♠7 ♥7 ♠9 ♥A ♦9         dipai        ♠J ♥J ♣9         */    }    public static void lookPai(String whos,ArrayList<String> list){        System.out.println(whos);        for(String pai:list){            System.out.print(pai+" ");        }        System.out.println();    }}

2、到手的牌是有顺序的

package org.westos_斗地主案例;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.TreeSet;/** *  * @author 小鑫 * */public class PokerGame2 {    public static void main(String[] args) {        //牌盒        HashMap<Integer, String> pokerBox = new HashMap<Integer,String>();        //造牌        String[] colors={"♥","♦","♠","♣"};        String [] nums={"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };        ArrayList<Integer> indexs = new ArrayList<Integer>();        int index=0;        //装进牌盒        for(String num:nums){            for(String color:colors){                pokerBox.put(index, num+color);                indexs.add(index);                index++;            }        }        //添加大王        //同时添加索引        System.out.println(index);//52        indexs.add(index);        pokerBox.put(index, "☺");        index++;        //添加小王        indexs.add(index);        pokerBox.put(index,"☹");        //System.out.println(index);//53        //System.out.println(pokerBox);        //System.out.println(indexs);        //洗牌,就是洗索引        Collections.shuffle(indexs);        Collections.shuffle(indexs);        Collections.shuffle(indexs);        //设置玩家和底牌        TreeSet<Integer> apple = new TreeSet<Integer>();        TreeSet<Integer> banner = new TreeSet<Integer>();        TreeSet<Integer> orange = new TreeSet<Integer>();        TreeSet<Integer> dipai = new TreeSet<Integer>();        //发牌,就是发索引        for(int i=0;i<indexs.size();i++){            if(i>=pokerBox.size()-3){                dipai.add(indexs.get(i));            }else if(i%3==0){                apple.add(indexs.get(i));            }else if(i%3==1){                banner.add(indexs.get(i));            }else if(i%3==2){                orange.add(indexs.get(i));            }        }        //看牌         lookPai("apple", apple, pokerBox);         lookPai("banner", banner, pokerBox);         lookPai("orange", orange, pokerBox);         lookPai("dipai", dipai, pokerBox);         /*         apple         2♥ 2♣ 3♥ 4♠ 5♦ 5♣ 6♥ 6♣ 8♣ 9♠ 10♦ 10♠ 10♣ J♥ J♦ Q♥ ☹          banner         A♥ A♦ 3♣ 4♥ 4♣ 5♠ 6♦ 7♦ 7♠ 7♣ 8♦ 9♣ 10♥ J♣ K♥ K♠ ☺          orange         A♠ A♣ 2♦ 2♠ 3♦ 4♦ 5♥ 6♠ 8♥ 8♠ 9♥ 9♦ J♠ Q♦ Q♠ Q♣ K♣          dipai         3♠ 7♥ K♦         */    }    private static void lookPai(String whos,TreeSet<Integer> list,HashMap<Integer,String> pokerBox) {        System.out.println(whos);        for(Integer in:list){            String pai=pokerBox.get(in);            System.out.print(pai+" ");        }        System.out.println();    }}

集合小结:

Collection:单列集合,存储元素为add()方法   List:元素有序,可以重复,每一个元素都存在整数索引                        遍历方式:1)迭代器:对象.iterator 2)普通for 3)增强for:数组和集合不能为null,否则空指针异常      ArrayList:底层数据结构是数组,查找快,增删慢,线程不安全,效率高      Vector:底层数据结构是数组,查找快,增删慢,线程安全,效率低      LinkedList:底层数据结构是链表,查找慢,增删快,线程不安全,效率高   Set:元素无序,不可以重复,保证元素的唯一性                    遍历方式:1)迭代器 2)增强for      HashSet:底层数据结构是哈希表,保证元素的唯一性,需要重写hashCode和equals方法      TreeSet:底层数据结构是二叉树,可以对元素进行排序,两张排序方式:               a:比较器排序(多使用匿名内部类实现)               b:自然排序 :必须实现Comparable接口,重写compareTo方法Map:双列集合,Map集合只跟键有关系,与值无关。(键相同,值覆盖)  存储元素为put()方法    Map集合的遍历方式:       1)根据键获取值 keySet()和get(Object key)       2)根据键值对获取键和值 entrySet()           Entry这个接口下两个方法获取键和值              getKey():获取键             getValue():获取值  HashMap:底层与HashSet一样,数据结构是哈希表,保证元素唯一,需要重写hashCode和equals方法,允许插入null键和null值                            存储元素put()方法,第一次存储时返回null,第二次存储返回上一次的值。  Hashtable:此处应该驼峰规则,与HashMap底层数据结构一致。             区别:       HashMap:同步,安全,效率低       Hashtable:不同步,不安全,效率高  LinkedHashMap:底层数据结构是链表和哈希表,链表保证元素有序(该有序指存储和取出顺序一致),哈希表保证元素唯一(重写hashCode和equals方法)  TreeMap: 底层与TreeSet一样,数据结构是二叉树,可以对元素实现排序,两张排序方式:           a:比较器排序(多使用匿名内部类实现)                         b:自然排序:必须实现Comparable接口,重写compareTo方法               TreeMap不允许插入null键,但是当存在键时,对应的值可以是null

day17

一、异常类

  • Throwable—>Exception Error
    • Exception:异常类
    • 子类: 1)编译时期异常:只要不是RuntimeException中的异常都属于编译时期异常:比如:IOException(IO流中的),ParseException(解析异常)
    • 2)运行时期异常:RuntimeException
    • 可能由于我们代码的逻辑不够严谨导致的问题举例,NullPointerException:空指针异常!
    • 需要个对象进行非空判断,来防止该问题的出现!

1、异常的表现

package org.westos_Exception_01;public class ExceptionDemo {    public static void main(String[] args) {        int a=10;        int b=0;        System.out.println(a/b);        //java.lang.ArithmeticException        System.out.println("sss");    }}

2、处理异常

  • 1)标准格式:try…catch…finally:捕获异常!
  • 2)throws 抛出异常
package org.westos_Exception_01;/** * 方式1:处理异常: *      try...catch...finally *      变形格式: *              try...catch *              try...catch...catch *              try...finally...(多线程的时候:Lock锁) * 经常使用的格式: * try{ *      //可能有很多行代码---->一旦有出现问题了 * }catch(异常类名 变量名){ *  输出语句处理 * } * @author 小鑫 * */public class ExceptionDemo2 {    public static void main(String[] args) {        int a=10;        int b=0;        try{            System.out.println(a/b);        }catch(ArithmeticException e){//catch内为具体异常类            System.out.println("除数不能为0");        }    }}

3、多个异常的处理

package org.westos_Exception_01;/**  *      1)方式1: *          针对多个异常分别的try...catch :在实际开发中,这种做法比较麻烦 *      2)方式2: *  *          try{ *              可能会出现问题的多个语句 *          }catch(异常类名1 变量名){ *              输出语句处理 *          }catch(异常类名2 变量名){ *              输出语句处理 *          } * 针对多个异常进行处理,第一个异常如果是大异常,那么后面可以不用再给了! * 将大异常放在小异常的后面; * @author 小鑫 * */public class ExceptionDemo3 {    public static void main(String[] args) {        method1();    }    private static void method1() {        int a=10;        int b=0;        int []arr={1,2,3};        try{            System.out.println(a/b);            System.out.println(arr[4]);        }catch(ArithmeticException e){            System.out.println("除数不能为0");        }catch(ArrayIndexOutOfBoundsException e){            System.out.println("该索引不存在");        }catch(Exception e){            System.out.println("出现问题");        }    }}

4、Jdk7版本的处理方法,平级处理

package org.westos_Exception_01;/** *  try{ *      //可能会出现问题的代码 *      //.... *      //... *  }catch(**异常类名1 | 异常类名2 ....变量名**){ *      处理异常... * } * 这个格式的注意事项: *          1)针对多个异常类名之间是一种平级关系 *          2)这种格式在实际开发中,虽然有多个异常,但是针对具体的异常给出具体的处理! * @author 小鑫 * */public class ExceptionDemo4 {    public static void main(String[] args) {        int a=10;        int b=0;        int []arr={1,2,3};        try{            System.out.println(a/b);            System.out.println(arr[4]);        }catch(ArithmeticException | ArrayIndexOutOfBoundsException e){            e.printStackTrace();        }        System.out.println("over");    }}

5、编译时期异常和运行时期异常

package org.westos_Exception_02;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * 编译时期异常:Java程序必须给予处理,否则编译不通过(必须显示处理) * 运行时期异常:可以处理,也可以像编译时期一样进行显示处理! * @author 小鑫 * */public class ExceptionDemo {    public static void main(String[] args) {        int a=10;        int b=0;        if(b!=0){            System.out.println(a/b);        }        System.out.println("天不错");        method();    }    private static void method(){        String s="2017-11-22";        SimpleDateFormat sdf = new SimpleDateFormat();        Date d;        try {            sdf.parse(s);        } catch (ParseException e) {            System.out.println("解析出问题了");        }    }}

6、捕获异常的标准格式: try…catch…finally

package org.westos_Exception_finally;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * 捕获异常的标准格式:   try...catch...finally * 用法: *      finally经常用在数据库中或者IO流中,用来释放资源的 *      finally中的代码一定会执行. *  *      finally中的不执行只有一种情况:就是Jvm退出了----->System.exit(0) ; *      当System.exit(0);时,Jvm退出,后边的逻辑代码都不会实现 * @author 小鑫 * */public class FinallyDemo {    public static void main(String[] args) {        String s="2017-11-22";        SimpleDateFormat sdf = new SimpleDateFormat();        try {            Date d = sdf.parse(s);        } catch (ParseException e) {            //e.printStackTrace();            System.out.println("解析出现问题");            //System.exit(0);        } finally{            System.out.println("此处代码一定会执行");        }        System.out.println("over");    }}

7、finally与return
* finally中的代码一定会执行,除非JVM退出。
* 此题之所以返回30,是因为在catch语句中已经有了返回路径,所以即使执行了finally中的代码,依然返回的是原返回路径的return值。

package org.westos_Exception_finally;/** * 如果catch里面有return语句,那么finally中的代码还会执行吗? * 如果可以,是在return前执行还是return后执行? * @author 小鑫 * */public class FinallyDemo2 {    public static void main(String[] args) {        System.out.println(getInt());    }    private static int getInt() {        int a = 10 ;        try{            System.out.println(a/0);            a = 20 ;        }catch(ArithmeticException e){            a = 30 ;            return a ;            /**             * 代码走到这里,return a,return 30 ,在这里形成了一个方法返回路径             * 但是,finally中代码只有在Jvm退出了,才不会执行,所以a = 40 ;             * 但是,由于之前已经返回路径,代码就要执行到return 前;             */        }finally{            a = 40 ;        }        return a;    }}

8、异常类常用方法
* public String getMessage():消息字符串
* public String toString():描述字符串:
* 1)当前类的全路径名称(指的是当前异常类名所在的包的全路径名称)
* 2)”: “(冒号和一个空格)
* public void printStackTrace():该方法是里面包含了消息字符串以及当前出现错误的异常的时候所描述哪个包下以及代码中具体的错误出现第几行,返回值是void,也就直接在控制台输出

package org.westos_Exception_02;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** *  try里面的代码一旦出问题了,那么Jvm java虚拟机就会针对这个问题抛出一个异常,然后和Catch里面的所描述异常进行是否匹配,如果一致就会产生一个异常对象,然后去处理这个异常对象,就会调用异常中的一些方法 * @author 小鑫 * */public class ExceptionDemo2 {    public static void main(String[] args) {        String s="2017-11-22";        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        try {            Date d = sdf.parse(s);            System.out.println(d);        } catch (ParseException e) {////ParseException e = new ParseException() ;            //e.printStackTrace();            System.out.println(e.getMessage());            //Unparseable date: "2017-11-22"            System.out.println(e.toString());            //java.text.ParseException: Unparseable date: "2017-11-22"            e.printStackTrace();//相当于给出一个页面            /*java.text.ParseException: Unparseable date: "2017-11-22"                at java.text.DateFormat.parse(DateFormat.java:357)                at org.westos_Exception_02.ExceptionDemo2.main(ExceptionDemo2.java:31)              */        }    }}

9、异常处理第二种方式:throws:抛出异常

package org.westos_Exception_02;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * 异常处理第二种方式: *  throws:抛出异常 *      在方法声明上抛出异常,由于,编译时期异常,调用者必须要处理 *      开发中尽量不在main()上抛出异常 * 在实际开发中: *          throws要比throw用的比较多,而try...catch...又比throws用的比较多! * @author 小鑫 * */public class ExceptionDemo3 {    public static void main(String[] args) {        method1();        try {            method2();        } catch (ParseException e) {            e.printStackTrace();        }    }    //throw    private static void method1() {        int a=10;        int b=0;        if(b==0){            System.out.println(a/b);            throw new  ArithmeticException();        }else{            System.out.println("不会出现问题");        }    }    //throws    private static void method2() throws ParseException{        String s="2017-11-22";        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        Date d = sdf.parse(s);        System.out.println(d);    }}

10、自定义异常类
自定义一个类,继承自Exception或者继承自RuntimeException

package org.westos_Exception_自定义异常类;import java.util.Scanner;/** * 自定义一个类,继承自Exception或者继承自RuntimeException * @author 小鑫 * */public class Demo {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.println("请输入一个分数");        int score = sc.nextInt();        Teacher t = new Teacher();        try {            t.check(score);        } catch (MyException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}package org.westos_Exception_自定义异常类;public class MyException extends Exception{    public MyException() {    }    public MyException(String message){        super(message);    }}package org.westos_Exception_自定义异常类;public class Teacher {    public void check(int score) throws MyException{        if(score>100 || score<0){            throw new MyException("分数应该在0到100之间");        }else{            System.out.println("分数正确");        }    }}

11、异常类的注意事项
异常的注意事项:
* 1)子类在重写父类中的方法的时候,如果父类中方法有抛出异常,那么子类重写的这个方法, 抛出异常不能够比父类中该方法异常大,(要么是父类中该方法异常的子类)(最起码应该保存一致)(父亲坏了,儿子不能比父亲更坏)
* 2)子类继承父类,要重写父类中的方法的时候,如果本身父类中该方法没有异常,那么在子类中重写该方法的时候,不能抛出异常,只能捕获异常!

package org.westos_Exception_注意事项;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ExcepDemo {}class Fu{    public void show() throws Exception{    }    public void method(){};}class Zi extends Fu{    @Override    public void show() throws Exception{        //子类重写父类方法,抛出异常不能比父类方法中的异常级别大,最多只能同级    }    @Override    public void method(){        String s="2017-11-22";        SimpleDateFormat sdf = new SimpleDateFormat();        //父类方法中没有抛出异常,子类重写此方法时,不能抛出异常,只能捕获异常。(其实也就是不能比父类级别大)        try {            Date d = sdf.parse(s);        } catch (ParseException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

12、面试题

 *          throwsthrow的区别? *           *          throws:抛出 *              后面跟的异常类名,可以跟多个异常类名,中间用逗号隔开 *              throws在方法声明上抛出,表示异常的一种可能性 *              由调用者去处理 *              throws表示抛出异常的一宗可能性 *          throw:抛出 *              后面跟的异常对象(匿名对象),只能跟具体的一个异常对象 *              throw在方法中的语句中抛出,表示异常的绝对性 *              有方法中某些语句处理 *  
 *  final,finalize,和finally的区别? *  区别: *     final:表示最终的,终态的意思 *      可以修饰类:类不能继承 *      可以修饰成员方法:成员方法被重写 *      可以修饰成员变量:此变量是一个常量   :自定义常量:  public static final int ORANGLE = 100 ; *     finalize:它表示通过gc垃圾回收器回收不用的对象或者是变量,System.gc():实质,调用的是重写了Object类中的 * finalize()方法,表示回收没有跟多引用对象或者变量等等... *     finally:不能单独使用,和try...catch...finally中一块使用,(异常,IO,数据库中中使用的),是用来释放资源 *      finally中的代码一定会执行,并且除非Java虚拟机Jvm退出了,才不会执行!

二、file类

1、File,是用来描述文件或者目录(文件夹)的路径的抽象表现形式
常用的构造方法:
* public File(String pathname):给定路径名以字符串来表示当前这个文件或者文件夹(开发中推荐使用第一种构造方法)
* public File(String parent,String child)根据 parent 路径名字符串和 child 路径名字符串创建一个新 File对象
* public File(File parent, String child)根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例

package org.westos_01;import java.io.File;public class FileDemo {    public static void main(String[] args) {        //创建一个File实例        //方式一        //public File(String pathname)        //给定路径名以字符串来表示当前这个文件或者文件夹(开发中推荐使用第一种构造方法)        File file = new File("F:\\demo\\a.txt");        System.out.println(file);        //方式二        //public File(String parent,String child)        //根据 parent 路径名字符串和 child 路径名字符串创建一个新 File对象         File file2 = new File("F:\\demo","a.txt");        System.out.println(file2);        //方式三        //public File(File parent, String child)        //根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例        File file3 = new File("F:\\demo");        File file4 = new File(file3,"a.txt");        System.out.println(file4);    }}

2、创建文件或者文件夹(目录)
使用File对象创建文件或者文件夹
* 里面跟创建有关的成员方法:
* public boolean mkdir()创建此抽象路径名指定的目录(文件夹)。
* 如果当前某个盘符下已经有了这个目录(文件夹),不会在创建了.
* public boolean createNewFile():创建文件的,如果已经有这个文件了,不在创建,并且该方法本身就会编译时期异常IOException
throws IOException
public boolean mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。(创建文件夹,文件夹不存在,才开始创建)
* 没有带盘符,默认到当前项目下创建文件或者文件夹..

package org.westos_02;import java.io.File;import java.io.IOException;public class FileDemo {    public static void main(String[] args) throws IOException {        //要在F盘创建一个文件夹file        //描述一下这个文件夹的抽象路径形式        //File对象封装这个文件夹        File file = new File("F:\\file");        //public boolean mkdir()        System.out.println("mkdi:"+file.mkdir());        //mkdi:true  说明创建成功        //在刚才创建的file文件夹(目录)中创建文件a.txt        //添加文件之前确保文件夹存在,否则报错        //描述这个文件夹的抽象路径形式        File file2 = new File("f:\\file\\a.txt");        //public boolean createNewFile()throws IOException        System.out.println(file2.createNewFile());        //true 创建成功        //在F盘创建aaa目录,再创建bbb---ccc---ddd子目录        //描述封装        File file3 = new File("F:\\aaa\\bbb\\ccc\\ddd");        //public boolean mkdirs()        System.out.println("mkdirs:"+file3.mkdirs());        //true 创建成功        //没带盘符时,默认当前项目创建文件        File file4 = new File("a.txt");        System.out.println(file4.createNewFile());        //true  创建成功    }}

3、删除文件或者文件夹
public boolean delete()删除此抽象路径名表示的文件或目录
* 删除不能删除带有文件或者文件夹的目录,就是当前文件夹或者文件为空时才能删除
* 删除多个目录时,必须逐一删除。

package org.westos_03;import java.io.File;import java.io.IOException;/** * public boolean delete()删除此抽象路径名表示的文件或目录 * @author 小鑫 * */public class FileDemo {    public static void main(String[] args) throws IOException {        //在当前项目下创建aaa\\bbb\\ccc        File file = new File("aaa\\bbb\\ccc");        System.out.println(file.mkdirs());//true        //在当前目录创建a.txt        File file2 = new File("a.txt");        System.out.println(file2.createNewFile());//true        //删除a.txt        //描述        File file3 = new File("a.txt");        System.out.println(file3.delete());//true        //删除aaa\\bbb\\ccc        //描述且逐一删除        File file4 = new File("aaa\\bbb\\ccc") ;        System.out.println(file4.delete());//true        File file5 = new File("aaa\\bbb") ;        System.out.println(file5.delete());//true        File file6 = new File("aaa") ;        System.out.println(file6.delete());//true    }}

4、File类中的重命名功能
public boolean renameTo(File dest)重新命名此抽象路径名表示的文件。
* 1)使用这个功能:当两个抽象路径一致,那么只是重命名
* 2)当这两个抽象路径不一致,有剪切并且改名了…

package org.westos_03;import java.io.File;public class FileDemo2 {    public static void main(String[] args) {        //描述当前项目存在的a.txt        File file = new File("a.txt");        //重命名        File file2 = new File("b.txt");        file.renameTo(file2);        //重命名成功        //将当前项目下的b.txt复制到F盘F:\\c.txt        File file3 = new File("b.txt");        //F:\\c.txt        File file4 = new File("F:\\c.txt");        file3.renameTo(file4);        //F盘中有c.txt  但是当前目录没有b.txt          //说明路径 不一致时,有剪切并且改名    }}

5、File类中的判断功能和获取功能
File类中的判断功能:
* public boolean isDirectory():判断是否是文件夹 经常用到
* public boolean isFile():判断是否是一个标准文件 经常用到
* public boolean canRead():判断是否可读
* public boolean canWriter():判断是否可写
* public boolean isHidden():判断是否是隐藏文件
* public boolean isAbsolute():判断此路径名是否是绝对路径
File类中的获取功能:
* public File getAbsolutePath():获取当前文件或者文件夹绝对路径
* public String getPath():获取相对路径
* public long length()返回由此抽象路径名表示的文件的长度
* public long lastModified()返回此抽象路径名表示的文件最后一次被修改的时间
* public String getName():获取名称

package org.westos_04;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;public class FileDemo {    public static void main(String[] args) throws IOException {        File file = new File("a.txt") ;        System.out.println(file.createNewFile());        //绝对路径        System.out.println(file.getAbsolutePath());        //F:\eclipse\Workspace\JavaSE_day17_文件file类\a.txt        //相对路径        System.out.println(file.getPath());//a.txt        System.out.println(file.getName());//a.txt        System.out.println(file.length());//10    存了一个helloworld        System.out.println(file.lastModified());//1511438635517        //格式化        Date d = new Date(1511438635517L);        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        String dateStr = sdf.format(d);        System.out.println(dateStr);        //2017-11-22 20:03:55    }}

6、File类的高就获取功能:
* public String[] list():返回对象是一个字符串数组,当前哪个一盘符下的所有的文件以及文件夹的字符串名称数组
* public File[] listFiles():返回对象是一个File数组,当前哪个盘下的所有的文件以及文件夹的File数组

package org.westos_05;import java.io.File;public class FileDemo {    public static void main(String[] args) {        //获取F盘下所有文件夹以及文件的字符串名称数组        //用File对象封装F盘        File file = new File("F:\\");        //public String[] list()        String[] strArray = file.list();        if(strArray!=null){            for(String s:strArray){                System.out.println(s);//JavaSE资料            }        }        System.out.println("--------------");        //public File[] listFiles():        File[] fileArray = file.listFiles();        if(fileArray!=null){            for(File f:fileArray){                System.out.println(f);//F:\JavaSE资料                System.out.println(f.getName());//JavaSE资料            }        }    }}

7、判断F盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
File[] fileArray = file.listFiles();

package org.westos_05;import java.io.File;/** * 判断F盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称 * 方式一: *  分析: *      1:用File对象封装E盘 *      2:获取当前e盘下的所有的文件以及文件夹的名称数组或者File数组 *      3):针对对象要做非空判断 *      4)遍历:File数组增强for遍历 *          获取每一个File对象 *          判断这个File对象是否是文件:isFile() *          如果是文件,还要判断是否以.jpg结尾 *          是,就输出 *          不是,不管 * @author 小鑫 * */public class FileTest {    public static void main(String[] args) {        File file = new File("F:\\");        File[] fileArray = file.listFiles();        if(fileArray!=null){            for(File f:fileArray){                if(file.isFile()){                    if(file.getName().endsWith(".jpg")){                        System.out.println(file.getName());                    }                }            }        }    }}

8、判断F盘下是否有后缀名为.jpg的文件,有就输出文件名称
public String[] list(FilenameFilter filter)

package org.westos_05;import java.io.File;import java.io.FilenameFilter;/** * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称 *  * 方式2:在获取的时候就已经满足条件 * 引出:文件名称过滤器 * public String[] list(FilenameFilter filter) * 参数是一个接口,(开发中使用的接口的匿名内部类的方式) *  实现一个方法: *   boolean accept(File dir, String name):这个方法的返回值是true * @author 小鑫 * */public class FileTest2 {    public static void main(String[] args) {        File file = new File("F:\\");        //public String[] list(FilenameFilter filter)        String[] strArray = file.list(new FilenameFilter() {            @Override            public boolean accept(File dir, String name) {                //return false;                File file = new File(dir,name);                boolean flag1 = file.isFile();                boolean flag2 = name.endsWith(".jpg");                return flag1 && flag2;                //return new File(dir,name).isFile() && name.endsWith(".jpg");            }        });    }}

三、IO流

1、针对输出流中写数据的方法:
* public abstract void write(int b):将指定的字节写入到输出流中
* public void write(byte[] b):将指定的字节数组写入到输出流中
* public void write(byte[] b, int off,int len):将字节数组的一部分写入到输出流中

package org.wetos_01;import java.io.FileOutputStream;import java.io.IOException;public class FileOutputStreamDemo {    public static void main(String[] args) throws IOException {        //创建一个文件输出流对象        FileOutputStream fos = new FileOutputStream("a.txt");        //public abstract void write(int b):将指定的字节写入到输出流中        fos.write(97);        fos.write(55);        fos.write(65);        fos.write(45);        // public void write(byte[] b):将指定的字节数组写入到输出流中        byte[] bys = { 97, 98, 99, 100, 101 };        fos.write(bys);        // public void write(byte[] b, int off,int len):实际开发中:该方法和读数据一块使用        fos.write(bys, 1, 3);        // 关闭资源        fos.close();    }}

2、需要写入换行符号
每一个系统他们对应IO这块换行符号是不一样的
* 对于windows操作系统来说:换行符号:\r\n
* 对于Linux操操作系统来说:\n
* 对于Mac操作系统来说:\r
3、给文件追加数据
public FileOutputStream(File file,boolean append):第二个参数设置为true,表示写入文

package org.wetos_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * 给文件追加数据 * public FileOutputStream(File file,boolean append):第二个参数设置为true,表示写入文 * @author 小鑫 * */public class FileOutputStreamDemo2 {    public static void main(String[] args) throws IOException {        //创建一个输出流对象        FileOutputStream fos = new FileOutputStream("b.txt",true) ;        //写数据        for(int i=0;i<10;i++){            fos.write(("hello"+i).getBytes());            //写一个换行符            fos.write("\r\n".getBytes());        }        //关闭资源        fos.close();    }}

4、IO流中加入异常操作
* 方式一:分别try…catch…
* 方式二:放在一块try…catch…
* 方式三:加入标准格式:try…catch…finally
A: 方式一:分别try…catch…

package org.wetos_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * 方式一:分别try...catch... * @author 小鑫 * */public class FileOutputStreamDemo3 {    public static void main(String[] args) {        FileOutputStream fos=null;            try {                fos=new FileOutputStream("a.txt");            } catch (FileNotFoundException e) {                e.printStackTrace();            }        //写数据            try {                fos.write("java".getBytes());            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        //释放资源            try {                fos.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }    }}

B:方式2:放在一块try…catch…

package org.wetos_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * 方式2:放在一块try...catch... * @author 小鑫 * */public class FileOutputStreamDemo4 {    public static void main(String[] args) {        try {            FileOutputStream fos = new FileOutputStream("b.txt");            fos.write("hello,java".getBytes());            fos.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

C:方式3:加入标准格式:try…catch…finally

package org.wetos_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * 方式3:加入标准格式:try...catch...finally * @author 小鑫 * */public class FileOutputStreamDemo5 {    public static void main(String[] args) {        FileOutputStream fos=null;        try {            fos=new FileOutputStream("c.txt");            //写数据            fos.write("hello,java".getBytes());        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            //释放资源            if(fos!=null){                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

5、IO流:设备和设备之间的数据传输
* 设备和设备指的是:硬盘和内存之间的数据传输
6、IO流的分类:
* 按流的方向分:
* 输入流:读数据的
* 输出流:写数据的
*
* 按数据类型分:用windows自带的记事本打开一个文件,如果自己可以看懂,一般情况使用字符流最好;如果打开之后,读不懂,那么使用字节流.
* 字节流:
* 字节输入流:InputStream
* 字节输出流:OutputStream
* 字符流
* 字符输入流:Reader
* 字符输出流:Writer
7、 需求:输出一个文本文件,给文本文件中写一句话:hello,IO,I’m coming…

package org.wetos_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;/** * 需求:输出一个文本文件,给文本文件中写一句话:hello,IO,I'm coming... *  使用字节流,来输出这个文件 *      OutputStream:字节输出流,该类是抽象类,不能实例化,但是这里提到文件,File类就是描述文件的. *      FileOutputStream:OutputStream的子类 *          构造方法: *              public FileOutputStream(String name) *          在抽象类的前面加上前缀: *              XXXInputStream *              XXXOutputStream *              XXXReader *              XXXWriter *      FileInputStream *      FileReader   *      FileWriter *  * 开发步骤" *      1)创建文件输出流对象 *      2)写数据 *      3)关闭资源 * @author 小鑫 * */public class OutputStreamDemo {    public static void main(String[] args) throws IOException {        //OutputStream os = new FileOutputStream("os.txt");//抽象类多态        FileOutputStream fos = new FileOutputStream("fos.txt") ;        fos.write("hello,IO,I'm coming...".getBytes());        //释放资源        fos.close();        //关闭流资源,关闭了就不能在写数据了        //该流对象输出完毕之后,不指向这个文件了,所以需要将它关闭    }}