day08-Stream-Exception-File【JAVA】

目录

Stream

Exception

File


Stream

  • 作用

    • 操作数组、集合,主要是减少遍历

  • 中间方法

    • 过滤【重点】

      • filter( s -> {return 条件;})

    • 排序【重点】

      • sorted()

    • 排序,指定规则

      • sorted( (o1, o2) -> { return 比较规则;} )

    • 去重

      • distinct()

    • 获取前几个

      • limit(long n)

    • 跳过前几个

      • skip(long n)

    • 做数据进一步加工,做映射

      • map( s -> return 加工后的值 )

    • 合并流

      • concat( 流1 , 流2)

  • 最终方法

    • 遍历【重点】

      • forEach(soutc)

    • 统计个数

      • count()

    • 最大值

      • max( (o1 , o2 ) -> { 排序规则 , 只能是升序} )

    • 最小值

      • min( (o1 , o2 ) -> { 排序规则 , 只能是升序} )

  • 收集流的方法

    • 目的:转化为数组、集合。因为实际开发中,用集合、数组更多

    • collect()

      • 收集为List

        • Collector.toList()

      • 收集为Set

        • Collector.toSet()

      • 收集为Map

        • Collector.toMap( k -> 返回健的映射, v -> 返回值的映射)

    • 收集为数组

      • toArray()

import java.util.Objects;
​
public class Student {
    private String name;
    private double score;
​
​
    public Student() {
    }
​
    public Student(String name, double score) {
        this.name = name;
        this.score = score;
    }
​
    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }
​
    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }
​
    /**
     * 获取
     * @return score
     */
    public double getScore() {
        return score;
    }
​
    /**
     * 设置
     * @param score
     */
    public void setScore(double score) {
        this.score = score;
    }
​
    public String toString() {
        return "Student{name = " + name + ", score = " + score + "}";
    }
​
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Double.compare(student.score, score) == 0 && Objects.equals(name, student.name);
    }
​
    @Override
    public int hashCode() {
        return Objects.hash(name, score);
    }
}
​
​
​

​
import java.util.ArrayList;
import java.util.Collections;
​
public class Test {
    /*
        需求:定义一个学生类【类中包含 姓名,成绩】,定义6个学生对象,添加到集合中
        实现下面的功能:实现学生的去重【如果学生对象名字和成绩相同,则认为是同一个人】,
        把学生中成绩及格的同学找出,然后成绩按照升序排序,  跳过前2个学生,
        最后把符合条件的学生的名字找出,输出结果
     */
    public static void main(String[] args) {
        // 定义6个学生对象
        Student s1 = new Student("张三", 100);
        Student s2 = new Student("李四", 48);
        Student s3 = new Student("王五", 95);
        Student s4 = new Student("赵六", 88);
        Student s5 = new Student("田七", 90);
        Student s6 = new Student("张三", 100);
        // 添加到集合中
        ArrayList<Student> list = new ArrayList<>();
        Collections.addAll(list, s1, s2, s3, s4, s5, s6);
​
        list.stream()
                .distinct()
                .filter(s -> s.getScore() >= 60)
                .sorted((o1, o2) -> {
                    return Double.compare(o1.getScore(), o2.getScore());
                })
                .skip(2)
                .map(s -> s.getName())
                .forEach(System.out::println);
    }
​
​
}
​

Exception

  • 分类

    • 编译时异常

      • 属于Exception

      • 在写代码的时候就爆红,需要处理

    • 运行时异常

      • 属于RuntimeException

      • 在程序运行的过程中才会出现

  • 处理异常方式【重点】

    • try...catch

      • 格式

        • try{ 可能出现异常的代码 }catch(Exception e){ 处理异常的方案 }

      • 好处

        • 代码可以继续往下运行

          public class Demo {
              /*
                  目标: 使用try...catch的方式处理异常
          ​
               */
              public static void main(String[] args) {
                  int[] arr = {11, 22, 33};
                  System.out.println(arr[0]);
                  try {
                      System.out.println(arr[3]); // 如果程序出现了异常,那么方法就停止了
                      System.out.println("走了吗???");
                  } catch (ArrayIndexOutOfBoundsException e) {
                      e.printStackTrace();
                      System.out.println(arr[2]);
                      System.out.println("这里的索引越界了~~");
                  }
                  int a = 10 / 2;
                  try {
                      int b = 10 / 0;
                  } catch (Exception e) {
                      e.printStackTrace();
                      System.out.println("这里出错啦~~");
          ​
                      System.out.println("toString():" + e.toString());
                      System.out.println("getMessage:" + e.getMessage());
                  }
                  System.out.println("程序结束");
              }
          }
          ​

    • throws

      • 格式

        • public static void 方法名() throws Exception{ }

      • 好处

        • 起到提醒的作用

          ​
          import java.text.ParseException;
          import java.text.SimpleDateFormat;
          import java.util.Date;
          ​
          public class Demo02 {
              /*
                   两种处理异常的方案:
                          1. try...catch  好处:程序可以继续往下运行
                          2. throws 异常  出现异常,方法就结束。
          ​
                          异常处理选择方案:
                              如果有多层调用,顶层要使用 try...catch
                              底层可以使用 try/catch 也可以使用 throws【如果要起到提示的作用】
          ​
               */
              public static void main(String[] args) {
                  try {
                      methodA();
                  } catch (ParseException e) {
          ​
                  }
              }
          ​
              public static void methodA() throws ParseException {
          ​
                  methodB();
              }
          ​
              private static void methodB() throws ParseException  {
                  methodC();
              }
          ​
              private static void methodC()throws ParseException {
                  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  Date date = sdf.parse("2020-01-01 03:03:03"); // throw
                  System.out.println(date);
                  System.out.println("程序结束~~");
              }
          ​
          ​
          }

    • finally

      • 执行特点

        • 一定会执行,如果方法是有返回值,那么就在执行返回之前 先执行finally里面的代码

          public class Demo02 {
              /*
                  finally 里面的代码的特点 :  一定会被执行
          ​
               */
              public static void main(String[] args) {
                  try {
                      int i = 10 / 0;
                  } catch (Exception e) {
                      System.out.println("做运算出现了问题....");
                      return;
                  } finally {
                      int a = 10 / 2;
                      System.out.println(a);
                  }
                  System.out.println("程序结束~~");
              }
          }
          ​

  • 自定义异常【了解】

    • 创建一个类继承 Exception / RuntimeException

    • 写上两个构造器 , 一个无参,一个参数为String

    • 在方法中,先通过 throw 抛出异常对象。 再在方法上throws 异常类名【运行时异常,这步可以不用】

​
public class U18Exception extends Exception{
    public U18Exception() {
    }
​
    public U18Exception(String message) { // 到时候可以把异常信息传递进来,交给父类
        super(message);
    }
}
​
​
​
​
/
​
​
public class User {
​
​
    // 我们需要接收一个整数,代表年龄
    public void register(int age)throws U18Exception{
        if(age >= 18){
            System.out.println("年龄是合法的~");
        }else{
            // 抛出异常  throw new  异常对象(错误信息);
            throw new U18Exception("年龄小于18");
        }
    }
​
    public void register2(int age){
        if(age >= 18){
            System.out.println("年龄是合法的~");
        }else{
            throw new User18Exception("年龄低于18岁,不合法");
        }
    }
​
    public void getPassword(String password){
        if(!password.matches("\\w{6,20}")){
            throw new PasswordException("密码长度不在[6,20]之间");
        }
    }
​
​
}
​
///
​
public class Test {
    public static void main(String[] args) {
        User u1 = new User();
        try {
            u1.register(16);
        } catch (U18Exception e) {
            e.printStackTrace();
        }
​
        u1.register2(16);
    }
}

File

  • 概念

    • 代表文件、文件夹

  • 创建对象

    • 构造器

      • File(String path)

      • File(String parent , String child)

      • File(File parent , String child)

    • 路径

      • 相对路径【推荐】

        • 没有盘符的路径

      • 绝对路径

        • 带盘符的路径

          import java.io.File;
          ​
          public class Demo01 {
              /*
                  目标:能够使用File提供的构造器创建对应的对象
          ​
               */
              public static void main(String[] args) {
                  // File f1 = new File("D:\\java_code\\JAVASE\\Java190\\day08-Stream-Exception-File\\file\\a.txt");
                  File f1 = new File("D:/java_code/JAVASE/Java190/day08-Stream-Exception-File/file/a.txt");
                  System.out.println(f1);
                  System.out.println(f1.length()); // 3
          ​
                  File f2 = new File("D:/java_code/JAVASE/Java190/day08-Stream-Exception-File/file", "a.txt");
          ​
                  File parent = new File("D:/java_code/JAVASE/Java190/day08-Stream-Exception-File/file");
                  File f3 = new File(parent, "aaaaa.txt");
                  System.out.println(f3);
                  System.out.println("-----------------------------------------------------------");
                  // 绝对路径:  带盘符 就是绝对路径
                  // 相对路径:  没有盘符的路径。相对某一个路径而言(根路径)
                  File f = new File("");
                  System.out.println(f.getAbsolutePath()); // D:\java_code\JAVASE\Java190
                  File f4 = new File("day08-Stream-Exception-File/file/a.txt");
                  System.out.println(f4.length()); // 3
          ​
              }
          }
          ​

  • 创建文件、删除文件的方法

    • 创建文件

      • createNewFile()

    • 创建文件夹

      • mkdir()

    • 创建多级文件夹

      • mkdirs()

    • 删除文件、文件夹

      • delete() 一定是一个空文件夹才能删除

        import java.io.File;
        import java.io.IOException;
        ​
        public class Demo {
            /*
                目标:能够使用File的Api实现对文件、文件夹的创建和删除
        ​
             */
            public static void main(String[] args) throws IOException {
                // 类名 对象名 = new 类名(文件的路径);
                System.out.println(new File("").getAbsolutePath());
                // 我想在 file文件下面创建一个b.txt
                File f1 = new File("D:\\java_code\\JAVASE\\Java190\\day08-Stream-Exception-File\\file\\b.txt");
                f1.createNewFile();
        ​
                // 我想在file下面创建一个temp的文件夹
                File f2 = new File("day08-Stream-Exception-File\\file\\temp");
                f2.mkdir();
        ​
                // 我想在file下面创建一个a文件夹,a下面有个b文件夹 ,b下面有个c文件夹
                File f3 = new File("day08-Stream-Exception-File\\file\\a/b/c");
                f3.mkdirs();
        ​
                // 我想把 temp删除
                File f4 = new File("day08-Stream-Exception-File\\file\\temp");
                f4.delete();
        ​
                // 我想把 a删除  ,删不了
                File f5 = new File("day08-Stream-Exception-File\\file\\a");
                f5.delete();
            }
        }

  • 判断文件类型、获取信息的方法

    • 判断是否存在

      • exists()

    • 判断是否为文件【重点】

      • isFile()

    • 判断是否为文件夹【重点】

      • isDirectory()

    • 获取文件大小

      • length()

    • 获取文件名字

      • getName()

    • 获取文件路径

      • getPath()

    • 获取文件的绝对路径【重点】

      • getAbsolutePath()

    • 获取最后修改时间

      • lastModified()

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.logging.SimpleFormatter;
​
public class Demo {
    /*
        目标 : 掌握File中常见的api
     */
    public static void main(String[] args) {
        // 关联一个不存在的文件路径
        File f1 = new File("day08-Stream-Exception-File/file/c.txt");
        // 关联一个a.txt 文件
        File f2 = new File("day08-Stream-Exception-File/file/a.txt");
        // 关联一个a文件夹
        File f3 = new File("day08-Stream-Exception-File/file/a");
        // public boolean exists()  判断当前文件对象,对应的文件路径是否存在,存在返回true
        System.out.println("c.txt是否存在:" + f1.exists()); // false
        System.out.println("a.txt是否存在:" + f2.exists()); // true
        // public boolean isFile()  判断当前文件对象指代的是否是文件,是文件返回true,反之为false
        // public boolean isDirectory() 判断当前文件对象指代的是否是文件夹,是文件夹返回true,反之为false
        System.out.println("a.txt是否为文件:" + f2.isFile());  // true
        System.out.println("a.txt是否为文件夹:" + f2.isDirectory()); // false
        System.out.println("a是否为文件:" + f3.isFile());  // false
        System.out.println("a是否为文件夹:" + f3.isDirectory()); // true
        // public String getName()  获取文件的名称(包含后缀)
        System.out.println("a.txt的文件名是:" + f2.getName()); // a.txt
        // public long length() 获取文件的大小,返回字节个数
        System.out.println("a.txt的内容大小是:" + f2.length()); // 3
        // public long lastModified()   获取文件的最后修改时间。
        long time = f2.lastModified();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time));
        // public String getPath()  获取创建文件对象时,使用的路径
        System.out.println("a.txt的路径:" + f2.getPath()); // day08-Stream-Exception-File\file\a.txt
        // public String getAbsolutePath()  获取绝对路径
        System.out.println("a.txt的绝对路径:" + f2.getAbsolutePath());
    }
}
​

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值