day10-File,IO流,字节流,Properties集合,ResourceBundle工具类,递归

今日目标

  • File类
  • IO流的介绍
  • IO流的分类
  • 字节输出流
  • 字节输入流
  • 字节缓冲区流
  • Properties集合
  • ResourceBundle工具类

    1 File类

    1.1 File类的介绍

  • java.io.File 类是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作
    day10 File,IO流,字节流,Properties集合,ResourceBundle工具类,递归 - 图1

    1.2 构造方法

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. /*
    4. File:它是文件和目录路径名的抽象表示
    5. 文件和目录可以通过File封装成对象
    6. File封装的对象仅仅是一个路径名。它可以是存在的,也可以是不存在的。
    7. 构造方法 :
    8. 1 File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
    9. 2 File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例
    10. 3 File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例
    11. 注意事项 : 父路径需要是一个目录路径
    12. */
    13. public class FileDemo1 {
    14. public static void main(String[] args) {
    15. // 使用File对象描述 D:\abc\caocao.jpg
    16. // String path = "D:\\abc\\caocao.jpg";
    17. String path = "D:/abc/caocao.jpg";
    18. //windows 系统 \
    19. //Mac Unix Linux 系统 /
    20. //java语言中描述目录的分隔符,两者都行
    21. //1 File(String pathname)
    22. File f1 = new File(path);
    23. //2 File(String parent, String child)
    24. String parent = "D:/abc";//父目录
    25. String child = "caocao.jpg";//子文件
    26. File f2 = new File(parent, child);
    27. //3 File(File parent, String child)
    28. File f3 = new File(new File(parent), child);
    29. System.out.println("f1 = " + f1);//f1 = D:\abc\caocao.jpg
    30. System.out.println("f2 = " + f2);//f2 = D:\abc\caocao.jpg
    31. System.out.println("f3 = " + f3);//f3 = D:\abc\caocao.jpg
    32. //结论:以上三种方式创建文件对象,都是可以的
    33. }
    34. }

    相对路径和绝对路径

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. /*
    4. 绝对路径 : 以盘符开始
    5. 相对路径 : 相对于IDEA工具项目下
    6. 相对路径的好处,更方便,更简洁的描述项目中的文件
    7. 能不能用相对路径描述非项目中的文件?
    8. 不能
    9. 项目中文件的绝对路径,将项目路径删除就是该文件的相对路径了!
    10. 导入模块时,一定要先将模块导入到项目中,否则你模块中文件的相对路径将会失效!!
    11. */
    12. public class PathDemo {
    13. public static void main(String[] args) {
    14. //绝对路径 : 以盘符开始 [可以表示电脑中任意位置的文件]
    15. File f1 = new File("D:/abc/caocao.jpg");
    16. File f2 = new File("D:\\codeInClass\\JavaEE146Code\\JavaSE\\a.txt");
    17. File f4 = new File("D:\\codeInClass\\JavaEE146Code\\JavaSE\\day10_demo\\b.txt");
    18. //相对路径 : 相对于IDEA工具项目下
    19. File f3 = new File("a.txt");
    20. //f2和f3表示的是相同的文件,但是相对路径更加简洁
    21. File f5 = new File("day10_demo\\b.txt");
    22. }
    23. }

    1.3 File类的创建功能

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. import java.io.IOException;
    4. /*
    5. File类的创建功能 :
    6. 1 public boolean createNewFile(): 创建一个新的空的文件,如果文件已经存在。不会覆盖返回false
    7. 2 public boolean mkdir() : 创建一个单级文件夹
    8. 3 public boolean mkdirs() : 创建一个多级文件夹 !!!
    9. */
    10. public class FileDemo2 {
    11. public static void main(String[] args) throws IOException {
    12. //创建文件
    13. File f1 = new File("day10_demo/file01.txt");
    14. boolean newFile = f1.createNewFile();
    15. System.out.println("newFile = " + newFile);
    16. //File f2 = new File("day10_demo/abc/file02.txt");
    17. //boolean newFile1 = f2.createNewFile();
    18. //报错了,注意:如果父目录不存在,此方法会有异常。不会主动创建父目录
    19. //System.out.println("newFile1 = " + newFile1);
    20. //创建目录(文件夹)
    21. //public boolean mkdir() : 创建一个单级文件夹
    22. File dir1 = new File("day10_demo\\aaa");
    23. boolean mkdir1 = dir1.mkdir();
    24. System.out.println("mkdir1 = " + mkdir1);
    25. File dir2 = new File("day10_demo\\bbb\\ccc\\ddd");
    26. boolean mkdir2 = dir2.mkdir();//mkdir方法不支持创建多级目录
    27. System.out.println("mkdir2 = " + mkdir2);
    28. //public boolean mkdirs() : 创建一个多级文件夹 !!!
    29. boolean mkdirs = dir2.mkdirs();
    30. System.out.println("mkdirs = " + mkdirs);
    31. }
    32. }

    1.4 File类的删除功能

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. import java.io.IOException;
    4. /*
    5. File类删除功能 :
    6. public boolean delete() 删除由此抽象路径名表示的文件或目录
    7. 注意 :
    8. 1 delete方法直接删除不走回收站。
    9. 2 如果删除的是一个文件,直接删除。
    10. 3 如果删除的是一个文件夹,需要先删除文件夹中的内容,最后才能删除文件夹
    11. */
    12. public class FileDemo3 {
    13. public static void main(String[] args) throws IOException {
    14. File f1 = new File("D:\\a.txt");
    15. // 1 public boolean createNewFile() : 创建一个新的空的文件
    16. System.out.println(f1.delete());
    17. File f2 = new File("day10_demo\\aaa");
    18. // 2 public boolean mkdir() : 创建一个单级文件夹
    19. System.out.println(f2.delete());
    20. File f3 = new File("day10_demo\\bbb");
    21. // 3 public boolean mkdirs() : 创建一个多级文件夹
    22. System.out.println(f3.delete());
    23. }
    24. }

    1.5 File类的判断和获取功能

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. /*
    4. File类判断和获取功能
    5. public boolean isDirectory() 测试此抽象路径名表示的File是否为目录
    6. public boolean isFile() 测试此抽象路径名表示的File是否为文件
    7. public boolean exists() 测试此抽象路径名表示的File是否存在
    8. public String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串
    9. public String getPath() 获取的是创建File对象给定的路径
    10. public String getName() 返回由此抽象路径名表示的文件或目录的名称
    11. */
    12. public class FileDemo4 {
    13. public static void main(String[] args) {
    14. File f1 = new File("day10_demo\\file01.txt");
    15. File f2 = new File("day10_demo\\aaa");
    16. File f3 = new File("day10_demo\\xxx.txt");//不存在的
    17. //public boolean isDirectory() 测试此抽象路径名表示的File是否为目录
    18. System.out.println("f1.isDirectory() = " + f1.isDirectory());//false
    19. System.out.println("f2.isDirectory() = " + f2.isDirectory());//true
    20. System.out.println("f3.isDirectory() = " + f3.isDirectory());//false
    21. //public boolean isFile() 测试此抽象路径名表示的File是否为文件
    22. System.out.println("f1.isFile() = " + f1.isFile());//true
    23. System.out.println("f2.isFile() = " + f2.isFile());//false
    24. System.out.println("f3.isFile() = " + f3.isFile());//false
    25. //public boolean exists() 测试此抽象路径名表示的File是否存在
    26. System.out.println("f1.exists() = " + f1.exists());//true
    27. System.out.println("f2.exists() = " + f2.exists());//true
    28. System.out.println("f3.exists() = " + f3.exists());//false
    29. //public String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串
    30. String absolutePath = f1.getAbsolutePath();
    31. System.out.println("absolutePath = " + absolutePath);
    32. //D:\codeInClass\JavaEE146Code\JavaSE\day10_demo\file01.txt
    33. //public String getPath() 获取的是创建File对象给定的路径【构造路径】
    34. System.out.println("f1.getPath() = " + f1.getPath());
    35. File f4 = new File("D:/abc/caocao.jpg");
    36. System.out.println("f4.getPath() = " + f4.getPath());
    37. //public String getName() 返回由此抽象路径名表示的文件或目录的名称
    38. System.out.println("f4.getName() = " + f4.getName());//caocao.jpg
    39. System.out.println("f2.getName() = " + f2.getName());//aaa
    40. }
    41. }

    1.6 File类高级获取功能

    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. /*
    4. File类高级获取功能
    5. public File[] listFiles() 返回此抽象路径名表示的目录中的文件和目录的File对象数组
    6. listFiles方法注意事项:
    7. 1 当调用者不存在时,返回null
    8. 2 当调用者是一个文件时,返回null
    9. 3 当调用者是一个空文件夹时,返回一个长度为0的数组
    10. 4 当调用者是一个有内容的文件夹时,将里面所有文件和文件夹的路径放在File数组中返回
    11. 5 当调用者是一个有隐藏文件的文件夹时,将里面所有文件和文件夹的路径放在File数组中返回,包含隐藏内容
    12. */
    13. public class FileDemo5 {
    14. public static void main(String[] args) {
    15. File file = new File("day10_demo\\bbb\\ccc");
    16. // 返回此抽象路径名表示的目录中的文件和目录的File对象数组
    17. File[] files = file.listFiles();
    18. // 遍历File类的数组
    19. for (File f : files) {
    20. // 拿到每一个文件的文字
    21. System.out.println(f.getName());
    22. }
    23. }
    24. }

    练习 :
    1. package com.itheima.file_demo;
    2. import java.io.File;
    3. import java.util.HashMap;
    4. /*
    5. 练习一 :统计一个文件夹中每种文件的个数并打印。
    6. 打印格式如下:
    7. txt:3个
    8. doc:1个
    9. jpg:2个
    10. 分析 :
    11. HashMap<String , Integer>集合 : 键存储的是文件扩展名 值存储的是文件类型出现的次数
    12. 主要使用的是HashMap集合的键唯一
    13. File -> listFiles() -> File[] -> 遍历数组拿到每一个File
    14. -> getName() 拿到每一个文件的名字 -> 根据.进行切割,拿到文件的扩展名
    15. 判断Map集合中是否存在键为此扩展名
    16. 有 : 扩展名 = hm.get(扩展名) + 1
    17. 没有 : 扩展名 = 1
    18. */
    19. public class FileTest1 {
    20. public static void main(String[] args) {
    21. //要统计的文件夹
    22. File dir = new File("D:/abc");
    23. //统计每种格式文件的个数,使用Map集合保存
    24. HashMap<String, Integer> countMap = new HashMap<>();
    25. //遍历dir中所有的子文件
    26. File[] files = dir.listFiles();
    27. for (File file : files) {
    28. if (file.isFile()) {
    29. //获取文件名
    30. String name = file.getName(); // xxxx.yyy
    31. String[] strArr = name.split("\\.");
    32. //文件名 aaa.jpg aaa.bbb.jpg
    33. String type = strArr[strArr.length - 1];
    34. //统计type出现的次数
    35. //1.判断countMap中是否存在type,
    36. if (countMap.containsKey(type)) {
    37. Integer count = countMap.get(type);
    38. //存在,原有次数+1
    39. count++;
    40. countMap.put(type, count);
    41. } else {
    42. //不存在,第一次
    43. countMap.put(type, 1);
    44. }
    45. }
    46. }
    47. System.out.println("countMap = " + countMap);
    48. //{jpg=2, pptx=1, xlsx=1, txt=1, java=4}
    49. }
    50. }

    2 IO流的介绍

    2.1 为什么要学习IO流

  • 通过变量,数组,或者集合存储数据

    • 都是不能永久化存储 , 因为数据都是存储在内存中
    • 只要代码运行结束,所有数据都会丢失
  • 使用IO流

    • 1,将数据写到文件中,实现数据永久化存储
    • 2,把文件中的数据读取到内存中(Java程序)

      2.2 什么是IO流

  • I 表示intput ,是数据从硬盘进内存的过程,称之为读。

  • O 表示output ,是数据从内存到硬盘的过程。称之为写
  • IO的数据传输,可以看做是一种数据的流动,按照流动的方向,以内存为参照物,进行读写操作

    • 简单来说:内存在读,内存在写

      2.3 IO流的分类

  • 按照流向区分

    • 输入流 : 用来读数据
    • 输出流 : 用来写数据
  • 按照类型区分
    • 字节流
    • 字符流
  • 注意 :

    • 字节流可以操作任意文件
    • 字符流只能操作纯文本文件
    • 用windows记事本打开能读的懂,那么这样的文件就是纯文本文件。

      3 字节流输出流

      3.1 字节输出流入门

      FileOutputStream类 :
  • OutputStream有很多子类,我们从最简单的一个子类开始。

  • java.io.FileOutputStream类是文件输出流,用于将数据写出到文件

    构造方法 :
  • public FileOutputStream(File file):创建文件输出流以写入由指定的 File对象表示的文件。

  • public FileOutputStream(String name): 创建文件输出流以指定的名称写入文件。

    1. public class FileOutputStreamConstructor throws IOException {
    2. public static void main(String[] args) {
    3. // 使用File对象创建流对象
    4. File file = new File("a.txt");
    5. FileOutputStream fos = new FileOutputStream(file);
    6. // 使用文件名称创建流对象
    7. FileOutputStream fos = new FileOutputStream("b.txt");
    8. }
    9. }

    字节输出流写数据快速入门
  1. 创建字节输出流对象。
  2. 写数据
  3. 释放资源
    1. package com.itheima.outputstream_demo;
    2. import java.io.FileNotFoundException;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. /*
    6. 字节输出流写数据快速入门 :
    7. 1 创建字节输出流对象。
    8. 2 写数据
    9. 3 释放资源
    10. */
    11. public class OutputStreamDemo1 {
    12. public static void main(String[] args) throws IOException {
    13. // 创建字节输出流对象
    14. // 如果指定的文件不存在 , 会自动创建文件
    15. // 如果文件存在 , 会把文件中的内容清空
    16. FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");
    17. // 写数据
    18. // 写到文件中就是以字节形式存在的
    19. // 只是文件帮我们把字节翻译成了对应的字符 , 方便查看
    20. fos.write(97);
    21. fos.write(98);
    22. fos.write(99);
    23. // 释放资源
    24. // while(true){}
    25. // 断开流与文件中间的关系
    26. fos.close();
    27. }
    28. }

    3.2 字节输出流写数据的方法

  • 字节流写数据的方法
    1. void write(int b) 一次写一个字节数据
    2. void write(byte[] b) 一次写一个字节数组数据
    3. void write(byte[] b, int off, int len) 一次写一个字节数组的部分数据
      1. package com.itheima.outputstream_demo;
      2. import java.io.FileNotFoundException;
      3. import java.io.FileOutputStream;
      4. import java.io.IOException;
      5. /*
      6. 字节流写数据的3种方式
      7. 1 void write(int b) 一次写一个字节数据
      8. 2 void write(byte[] b) 一次写一个字节数组数据
      9. 3 void write(byte[] b, int off, int len) 一次写一个字节数组的部分数据
      10. */
      11. public class OutputStreamDemo2 {
      12. public static void main(String[] args) throws IOException {
      13. // 创建字节输出流对象
      14. FileOutputStream fos = new FileOutputStream("day11_demo\\a.txt");
      15. // 写数据
      16. // 1 void write(int b) 一次写一个字节数据
      17. fos.write(97);
      18. fos.write(98);
      19. fos.write(99);
      20. // 2 void write(byte[] b) 一次写一个字节数组数据
      21. byte[] bys = {65, 66, 67, 68, 69};
      22. fos.write(bys);
      23. // 3 void write(byte[] b, int off, int len) 一次写一个字节数组的部分数据
      24. fos.write(bys, 0, 3);
      25. // 释放资源
      26. fos.close();
      27. }
      28. }

      3.3 写数据的换行和追加写入

      字节流写数据的换行和追加写入
  1. 字节流写数据如何实现换行呢?
    写完数据后,加换行符
    windows : \r\n
    linux : \n
    mac : \r
  2. 字节流写数据如何实现追加写入呢?
    通过构造方法 : public FileOutputStream(String name,boolean append)
    创建文件输出流以指定的名称写入文件。如果第二个参数为true ,不会清空文件里面的内容
    1. package com.itheima.outputstream_demo;
    2. import java.io.FileNotFoundException;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. public class OutputStreamDemo3 {
    6. public static void main(String[] args) throws IOException {
    7. //1. 创
    8. //FileOutputStream fos = new FileOutputStream("day10_demo\\file\\file02.txt"); //默认不拼接
    9. FileOutputStream fos =
    10. new FileOutputStream("day10_demo\\file\\file02.txt",true); //可以续写
    11. //2. 写
    12. String str = "Hello\r\nWorld!\nHello\rJava\n";
    13. fos.write(str.getBytes());//先把字符串转为字节数组,写出
    14. //3. 关
    15. fos.close();
    16. }
    17. }

    4 字节输入流

    4.1 字节输入流介绍

  • 字节输入流类
    • InputStream类 : 字节输入流最顶层的类 , 抽象类
      —- FileInputStream类 : FileInputStream extends InputStream
  • 构造方法
    • public FileInputStream(File file) : 从file类型的路径中读取数据
    • public FileInputStream(String name) : 从字符串路径中读取数据
  • 步骤

    • 创建输入流对象
    • 读数据
    • 释放资源
      1. package com.itheima.inputstream_demo;
      2. import java.io.FileInputStream;
      3. import java.io.IOException;
      4. /*
      5. 字节输入流写数据快速入门 : 一次读一个字节
      6. 第一部分 : 字节输入流类
      7. InputStream类 : 字节输入流最顶层的类 , 抽象类
      8. --- FileInputStream类 : FileInputStream extends InputStream
      9. 第二部分 : 构造方法
      10. public FileInputStream(File file) : 从file类型的路径中读取数据
      11. public FileInputStream(String name) : 从字符串路径中读取数据
      12. 第三部分 : 字节输入流步骤
      13. 1 创建输入流对象
      14. 2 读数据
      15. 3 释放资源
      16. */
      17. public class FileInputStreamDemo1 {
      18. public static void main(String[] args) throws IOException {
      19. // 创建字节输入流对象
      20. // 读取的文件必须存在 , 不存在则报错
      21. FileInputStream fis = new FileInputStream("day11_demo\\a.txt");
      22. // 读数据 , 从文件中读到一个字节
      23. // 返回的是一个int类型的字节
      24. // 如果想看字符, 需要强转
      25. int by = fis.read();
      26. System.out.println((char) by);
      27. // 释放资源
      28. fis.close();
      29. }
      30. }

      4.2 字节输入流读多个字节

      1. package com.itheima.inputstream_demo;
      2. import java.io.FileInputStream;
      3. import java.io.FileNotFoundException;
      4. import java.io.FileOutputStream;
      5. import java.io.IOException;
      6. /*
      7. FileInputStream类 :
      8. public int read(byte[] b):
      9. 1 从输入流读取最多b.length个字节的数据
      10. 2 返回的是真实读到的数据个数
      11. 3 如果不到数据 , 那么会返回-1
      12. 需求1 : 在当前模块下创建一个文件 , 文件存储数据hello world , 定义长度为5的字节数组进行读取数据
      13. String类
      14. public String(byte[] bys) : 把字节数组中的内容转成一个字符串
      15. public String(byte[] bytes, int startIndex, int length) : 把字节数组的一部分转成字符串
      16. */
      17. public class FileInputStreamDemo5 {
      18. public static void main(String[] args) {
      19. //1. 创
      20. try (FileInputStream fis = new FileInputStream("day10_demo\\file\\file01.txt");) {
      21. //2. 读
      22. //public int read(byte[] b):
      23. // 从输入流读取最多b.length个字节的数据,回的是真实读到的数据个数,读取完成那么会返回-1
      24. /*
      25. byte[] buf = new byte[100];
      26. int len = fis.read(buf); //len就是读取的有效字节个数
      27. System.out.println("len=" + len +":"+ new String(buf));//把字节数组编程字符串输出
      28. System.out.println("len=" + len +":"+ new String(buf,0,len));//把字节数组编程字符串输出
      29. */
      30. //使用循环读取
      31. int len; //每次读取的有效数据个数
      32. byte[] buf = new byte[5];
      33. while ((len = fis.read(buf)) != -1) {
      34. //把读取的有效字节数据变成字符串
      35. System.out.println(new String(buf, 0, len));
      36. }
      37. //3. 关
      38. } catch (IOException e) {
      39. e.printStackTrace();
      40. }
      41. }
      42. }

      4.3 图片的拷贝

      1. package com.itheima.inputstream_demo;
      2. import java.io.FileInputStream;
      3. import java.io.FileNotFoundException;
      4. import java.io.FileOutputStream;
      5. import java.io.IOException;
      6. /*
      7. 需求 : 把 "图片路径\xxx.jpg" 复制到当前模块下
      8. 分析:
      9. 复制文件,其实就把文件的内容从一个文件中读取出来(数据源),然后写入到另一个文件中(目的地)
      10. 数据源:
      11. xxx.jpg --- 读数据 --- FileInputStream
      12. 目的地:
      13. 模块名称\copy.jpg --- 写数据 --- FileOutputStream
      14. */
      15. public class FileInputStreamDemo2 {
      16. public static void main(String[] args) throws IOException {
      17. // 创建字节输入流对象
      18. FileInputStream fis = new FileInputStream("D:\\传智播客\\安装包\\好看的图片\\liqin.jpg");
      19. // 创建字节输出流
      20. FileOutputStream fos = new FileOutputStream("day11_demo\\copy.jpg");
      21. // 一次读写一个字节
      22. int by;
      23. while ((by = fis.read()) != -1) {
      24. fos.write(by);
      25. }
      26. // 释放资源
      27. fis.close();
      28. fos.close();
      29. }
      30. }

      4.4 异常的捕获处理

  • JDK7版本之前处理方式 : 手动释放资源

    1. package com.itheima.inputstream_demo;
    2. import java.io.FileInputStream;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. /*
    6. 需求 : 对上一个赋值图片的代码进行使用捕获方式处理
    7. */
    8. public class FileInputStreamDemo4 {
    9. public static void main(String[] args) {
    10. FileInputStream fis = null ;
    11. FileOutputStream fos = null;
    12. try {
    13. // 创建字节输入流对象
    14. fis = new FileInputStream("D:\\传智播客\\安装包\\好看的图片\\liqin.jpg");
    15. // 创建字节输出流
    16. fos = new FileOutputStream("day11_demo\\copy.jpg");
    17. // 一次读写一个字节
    18. int by;
    19. while ((by = fis.read()) != -1) {
    20. fos.write(by);
    21. }
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. } finally {
    25. // 释放资源
    26. if(fis != null){
    27. try {
    28. fis.close();
    29. } catch (IOException e) {
    30. e.printStackTrace();
    31. }
    32. }
    33. // 释放资源
    34. if(fos != null){
    35. try {
    36. fos.close();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. }
    43. }
  • JDK7版本优化处理方式 : 自动释放资源

    • JDK7优化后可以使用 try-with-resource 语句 , 该语句确保了每个资源在语句结束时自动关闭。
      简单理解 : 使用此语句,会自动释放资源 , 不需要自己在写finally代码块了
    • 格式 :
      1. 格式 :
      2. try (创建流对象语句1 ; 创建流对象语句2 ...) {
      3. // 读写数据
      4. } catch (IOException e) {
      5. 处理异常的代码...
      6. }
      7. 举例 :
      8. try (
      9. FileInputStream fis1 = new FileInputStream("day11_demo\\a.txt") ;
      10. FileInputStream fis2 = new FileInputStream("day11_demo\\b.txt") )
      11. {
      12. // 读写数据
      13. } catch (IOException e) {
      14. 处理异常的代码...
      15. }
  • 代码实践

    1. package com.itheima.inputstream_demo;
    2. import java.io.FileInputStream;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. /*
    6. JDK7版本优化处理方式
    7. 需求 : 对上一个赋值图片的代码进行使用捕获方式处理
    8. */
    9. public class FileInputStreamDemo5 {
    10. public static void main(String[] args) {
    11. try (
    12. // 创建字节输入流对象
    13. FileInputStream fis = new FileInputStream("D:\\传智播客\\安装包\\好看的图片\\liqin.jpg");
    14. // 创建字节输出流
    15. FileOutputStream fos = new FileOutputStream("day11_demo\\copy.jpg")
    16. ) {
    17. // 一次读写一个字节
    18. int by;
    19. while ((by = fis.read()) != -1) {
    20. fos.write(by);
    21. }
    22. // 释放资源 , 发现已经灰色 , 提示多余的代码 , 所以使用 try-with-resource 方式会自动关流
    23. // fis.close();
    24. // fos.close();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. }

    4.4 对复制图片的代码进行使用一次读写一个字节数组的方式进行改进

  • FileInputStream类 :

    • public int read(byte[] b) : 从输入流读取最多b.length个字节的数据, 返回的是真实读到的数据个数
  • 对复制图片的代码进行使用一次读写一个字节数组的方式进行改进

    1. package com.itheima.inputstream_demo;
    2. import java.io.FileInputStream;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. /*
    6. 需求2 : 对复制图片的代码进行使用一次读写一个字节数组的方式进行改进
    7. FileInputStream类 :
    8. public int read(byte[] b):
    9. 1 从输入流读取最多b.length个字节的数据
    10. 2 返回的是真实读到的数据个数
    11. 复制图片
    12. 数据源 : D:\传智播客\安装包\好看的图片\liqin2.jpg
    13. 目的地 : day11_demo\copy.jpg
    14. */
    15. public class FileInputStreamDemo7 {
    16. public static void main(String[] args) {
    17. //1.创建流(输入,输出)
    18. try (FileInputStream fis = new FileInputStream("D:\\abc\\caocao.jpg");
    19. FileOutputStream fos =
    20. new FileOutputStream("day10_demo\\file\\caocao2.jpg");) {
    21. //2.读,写
    22. //一次读取一个字节方式拷贝: 慢
    23. /*
    24. int b;//表示每次读取的字节
    25. while ((b = fis.read()) != -1) {//读一个字节
    26. fos.write(b);//写一个字节
    27. }*/
    28. //一次读取一个字节数组方式拷贝: 快
    29. int len;
    30. byte[] buf = new byte[8*1024];
    31. while ((len = fis.read(buf)) != -1) {//读取字节放到buf数组,有效的len个字节
    32. //把有效的字节数据写出去
    33. fos.write(buf,0,len);
    34. }
    35. //3.释放资源 [先开后关] 自动关流
    36. } catch (IOException e) {
    37. System.out.println("e = " + e);
    38. }
    39. }
    40. }

    5 字节缓冲区流

    5.1 字节缓冲流概述

  • 字节缓冲流:

    • BufferOutputStream:缓冲输出流
    • BufferedInputStream:缓冲输入流
  • 构造方法:
    • 字节缓冲输出流:BufferedOutputStream(OutputStream out)
    • 字节缓冲输入流:BufferedInputStream(InputStream in)
  • 为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?

    • 字节缓冲流仅仅提供缓冲区,不具备读写功能 , 而真正的读写数据还得依靠基本的字节流对象进行操作

      5.2 字节缓冲流案例

      1. package com.itheima.bufferedstream_demo;
      2. import java.io.*;
      3. /*
      4. 字节缓冲流:
      5. BufferOutputStream:缓冲输出流
      6. BufferedInputStream:缓冲输入流
      7. 构造方法:
      8. 字节缓冲输出流:BufferedOutputStream(OutputStream out)
      9. 字节缓冲输入流:BufferedInputStream(InputStream in)
      10. 为什么构造方法需要的是字节流,而不是具体的文件或者路径呢?
      11. 字节缓冲流仅仅提供缓冲区,不具备读写功能 , 而真正的读写数据还得依靠基本的字节流对象进行操作
      12. 需求 : 使用缓冲流进行复制文件
      13. */
      14. public class BufferedStreamDemo1 {
      15. public static void main(String[] args) throws IOException {
      16. // 创建高效的字节输入流对象
      17. // 在底层会创建一个长度为8192的数组
      18. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\传智播客\\安装包\\好看的图片\\liqin.jpg"));
      19. // 创建高效的字节输出流
      20. // 在底层会创建一个长度为8192的数组
      21. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day11_demo\\copy.jpg"));
      22. // 使用高效流 , 一次读写一个字节
      23. int by;
      24. while ((by = bis.read()) != -1) {
      25. bos.write(by);
      26. }
      27. // byte[] bys = new byte[1024];
      28. // int len;// 每次真实读到数据的个数
      29. // while ((len = bis.read(bys)) != -1) {
      30. // bos.write(bys, 0, len);
      31. // }
      32. // 释放资源
      33. // 在底层会把基本的流进行关闭
      34. bis.close();
      35. bos.close();
      36. }
      37. }

      5.3 缓冲流一次读写一个字节原理

      day10 File,IO流,字节流,Properties集合,ResourceBundle工具类,递归 - 图2

      5.4 四种方式复制视频文件

      1. package com.itheima.bufferedstream_demo;
      2. import java.io.*;
      3. /*
      4. 基本流和高效流效率对比
      5. 需求:把“xxx.avi”复制到模块目录下的“copy.avi” , 使用四种复制文件的方式 , 打印所花费的时间
      6. 四种方式:
      7. 1 基本的字节流一次读写一个字节
      8. 2 基本的字节流一次读写一个字节数组
      9. 3 缓冲流一次读写一个字节
      10. 4 缓冲流一次读写一个字节数组
      11. 分析 :
      12. 数据源 : D:\a.wmv
      13. 目的地 : "day10_demo\copy.wmv"
      14. */
      15. public class BufferedStreamDemo2 {
      16. public static void main(String[] args) {
      17. //高效流数组拷贝花费时间:236
      18. //基本流数组拷贝花费时间:221
      19. //高效流单字节拷贝花费时间:3318
      20. //基本流单字节拷贝花费时间: 332,727
      21. //结论:
      22. // 1.高效流,基本流数组拷贝方式相差不大。高效流的单字节拷贝方式远高于基本流单字节拷贝方式
      23. // 2.数组拷贝方式比单字节拷贝方式更高效
      24. new Thread(() -> {
      25. copy1("D:/abc/src1.wmv", "D:/abc/copy/dest1.wmv");
      26. }).start();
      27. new Thread(() -> {
      28. copy2("D:/abc/src2.wmv", "D:/abc/copy/dest2.wmv");
      29. }).start();
      30. new Thread(() -> {
      31. copy3("D:/abc/src3.wmv", "D:/abc/copy/dest3.wmv");
      32. }).start();
      33. new Thread(() -> {
      34. copy4("D:/abc/src4.wmv", "D:/abc/copy/dest4.wmv");
      35. }).start();
      36. }
      37. //基本流单字节拷贝
      38. public static void copy1(String src, String dest) {
      39. System.out.println("基本流单字节拷贝开始.....");
      40. long t1 = System.currentTimeMillis();
      41. try (FileInputStream fis = new FileInputStream(src);
      42. FileOutputStream fos = new FileOutputStream(dest);
      43. ) {
      44. //2.读,写
      45. int b;//表示每次读取的字节
      46. while ((b = fis.read()) != -1) {//读一个字节
      47. fos.write(b);//写一个字节
      48. }
      49. } catch (IOException e) {
      50. System.out.println("e = " + e);
      51. }
      52. long t2 = System.currentTimeMillis();
      53. System.out.println("基本流单字节拷贝花费时间:" + (t2 - t1));
      54. }
      55. //高效流单字节拷贝
      56. public static void copy2(String src, String dest) {
      57. System.out.println("高效流单字节拷贝开始.....");
      58. long t1 = System.currentTimeMillis();
      59. try (FileInputStream fis = new FileInputStream(src);
      60. BufferedInputStream bis = new BufferedInputStream(fis);//把基本流改造为高效流
      61. FileOutputStream fos = new FileOutputStream(dest);
      62. BufferedOutputStream bos = new BufferedOutputStream(fos) //把基本流改造为高效流
      63. ) {
      64. //2.读,写
      65. int b;//表示每次读取的字节
      66. while ((b = bis.read()) != -1) {//读一个字节
      67. bos.write(b);//写一个字节
      68. }
      69. } catch (IOException e) {
      70. System.out.println("e = " + e);
      71. }
      72. long t2 = System.currentTimeMillis();
      73. System.out.println("高效流单字节拷贝花费时间:" + (t2 - t1));
      74. }
      75. //基本流数组拷贝
      76. public static void copy3(String src, String dest) {
      77. System.out.println("基本流数组拷贝开始.....");
      78. long t1 = System.currentTimeMillis();
      79. try (FileInputStream fis = new FileInputStream(src);
      80. FileOutputStream fos = new FileOutputStream(dest);
      81. ) {
      82. //2.读,写
      83. int len;
      84. byte[] buf = new byte[8 * 1024];
      85. while ((len = fis.read(buf)) != -1) {
      86. fos.write(buf, 0, len);
      87. }
      88. } catch (IOException e) {
      89. System.out.println("e = " + e);
      90. }
      91. long t2 = System.currentTimeMillis();
      92. System.out.println("基本流数组拷贝花费时间:" + (t2 - t1));
      93. }
      94. //高效流数组拷贝
      95. public static void copy4(String src, String dest) {
      96. System.out.println("高效流数组拷贝开始.....");
      97. long t1 = System.currentTimeMillis();
      98. try (FileInputStream fis = new FileInputStream(src);
      99. BufferedInputStream bis = new BufferedInputStream(fis);//把基本流改造为高效流
      100. FileOutputStream fos = new FileOutputStream(dest);
      101. BufferedOutputStream bos = new BufferedOutputStream(fos) //把基本流改造为高效流
      102. ) {
      103. //2.读,写
      104. int len;
      105. byte[] buf = new byte[8 * 1024];
      106. while ((len = bis.read(buf)) != -1) {
      107. bos.write(buf, 0, len);
      108. }
      109. } catch (IOException e) {
      110. System.out.println("e = " + e);
      111. }
      112. long t2 = System.currentTimeMillis();
      113. System.out.println("高效流数组拷贝花费时间:" + (t2 - t1));
      114. }
      115. }

      6 Properties

      6.1 Properties集合的概述

  • properties是一个Map体系的集合类

    • public class Properties extends Hashtable <Object,Object>
  • 为什么在IO流部分学习Properties
    • Properties中有跟IO相关的方法
  • 当做双列集合使用

    • 不需要加泛型 , 工作中只存字符串

      1. package com.itheima.properties_demo;
      2. import java.util.Map;
      3. import java.util.Properties;
      4. import java.util.Set;
      5. /*
      6. 1 properties是一个Map体系的集合类
      7. - `public class Properties extends Hashtable <Object,Object>`
      8. 2 为什么在IO流部分学习Properties
      9. - Properties中有跟IO相关的方法
      10. 3 当做双列集合使用
      11. - 不需要加泛型 , 工作中只存字符串
      12. */
      13. public class PropertiesDemo1 {
      14. public static void main(String[] args) {
      15. // 创建集合对象
      16. Properties properties = new Properties();
      17. // 添加元素
      18. properties.put("it001" , "张三");
      19. properties.put("it002" , "李四");
      20. properties.put("it003" , "王五");
      21. // 遍历集合 : 键找值
      22. Set<Object> set = properties.keySet();
      23. for (Object key : set) {
      24. System.out.println(key + "---" + properties.get(key));
      25. }
      26. System.out.println("========================");
      27. // 遍历集合 : 获取对对象集合 , 获取键和值
      28. Set<Map.Entry<Object, Object>> set2 = properties.entrySet();
      29. for (Map.Entry<Object, Object> entry : set2) {
      30. Object key = entry.getKey();
      31. Object value = entry.getValue();
      32. System.out.println(key + "---" + value);
      33. }
      34. }
      35. }

      6.2 Properties作为集合的特有方法

  • Object setProperty(String key, String value) 设置集合的键和值,都是String类型,相当于put方法

  • String getProperty(String key) 使用此属性列表中指定的键搜索属性 , 相当于get方法
  • Set stringPropertyNames() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 , 相当于keySet方法

    1. package com.itheima.properties_demo;
    2. import java.util.Properties;
    3. import java.util.Set;
    4. /*
    5. Properties作为集合的特有方法
    6. Object setProperty(String key, String value) 设置集合的键和值,都是String类型,相当于put方法
    7. String getProperty(String key) 使用此属性列表中指定的键搜索属性 , 相当于get方法
    8. Set<String> stringPropertyNames() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串 , 相当于keySet方法
    9. */
    10. public class PropertiesDemo2 {
    11. public static void main(String[] args) {
    12. // 创建集合对象
    13. Properties properties = new Properties();
    14. // 添加元素
    15. properties.setProperty("it001", "张三");
    16. properties.setProperty("it002", "李四");
    17. properties.setProperty("it003", "王五");
    18. // 遍历集合 : 键找值
    19. Set<String> set = properties.stringPropertyNames();
    20. for (String key : set) {
    21. System.out.println(key + "---" + properties.getProperty(key));
    22. }
    23. }
    24. }

    6.3 properties中和IO相关的方法

  • void load(InputStream inStream) 以字节流形式 , 把文件中的键值对, 读取到集合中

  • void load(Reader reader) 以字符流形式 , 把文件中的键值对, 读取到集合中
  • void store(OutputStream out, String comments) 把集合中的键值对,以字节流形式写入文件中 , 参数二为注释
  • void store(Writer writer, String comments) 把集合中的键值对,以字符流形式写入文件中 , 参数二为注释

    1. package com.itheima.properties_demo;
    2. import java.io.FileInputStream;
    3. import java.io.FileNotFoundException;
    4. import java.io.FileOutputStream;
    5. import java.io.IOException;
    6. import java.util.Properties;
    7. /*
    8. 2 和IO流结合的方法
    9. void load(InputStream inStream) : 以字节流形式 , 把文件中的键值对, 读取到集合中
    10. // void load(Reader reader) 以字符流形式 , 把文件中的键值对, 读取到集合中
    11. void store(OutputStream out, String comments) 把集合中的键值对,以字节流形式写入文件中 , 参数二为注释
    12. // void store(Writer writer, String comments) 把集合中的键值对,以字符流形式写入文件中 , 参数二为注释
    13. */
    14. public class PropertiesDemo3 {
    15. public static void main(String[] args) {
    16. //storeTest(); //保存配置信息到配置文件
    17. loadTest(); //读取配置文件的信息到内存
    18. }
    19. private static void loadTest() {
    20. Properties dbPro = new Properties();
    21. System.out.println("dbPro = " + dbPro);
    22. //dbPro = {}
    23. //void load(InputStream inStream) : 以字节流形式 , 把文件中的键值对, 读取到集合中
    24. try (FileInputStream fis = new FileInputStream("day10_demo\\db.properties")) {
    25. dbPro.load(fis); //将流中关联配置文件中的键值对数据放到dbPro对象中
    26. System.out.println("dbPro = " + dbPro);
    27. //dbPro = {password=1234, username=root}
    28. } catch (IOException e) {
    29. e.printStackTrace();
    30. }
    31. }
    32. private static void storeTest() {
    33. Properties pro = new Properties();
    34. pro.setProperty("username", "root");
    35. pro.setProperty("password", "1234");
    36. //把pro集合中的键值对数据保存到文件中
    37. try (
    38. FileOutputStream fos = new FileOutputStream("day10_demo\\db.properties");
    39. //用来保存键值对数据的文件,一般叫做属性集文件,配置文件,后缀一般就是 .properties
    40. ) {
    41. //将内存中pro对象数据保存到db.properties文件中
    42. pro.store(fos, "this is comments! 中文注释");
    43. } catch (IOException e) {
    44. e.printStackTrace();
    45. }
    46. }
    47. }

    7 ResourceBundle加载属性文件

    学习目标

  • 能够熟练使用ResourceBundle工具类快速读取属性文件的值

    内容讲解

    【1】API介绍

    java.util.ResourceBundle它是一个抽象类,我们可以使用它的子类PropertyResourceBundle来读取以.properties结尾的配置文件。

    通过静态方法直接获取对象:

    ```java static ResourceBundle getBundle(String baseName) 可以根据名字直接获取默认语言环境下的属性资源。 参数注意: baseName

    1. 1.属性集名称不含扩展名。

    2.属性集文件是在src目录中的

比如:src中存在一个文件 user.properties ResourceBundle bundle = ResourceBundle.getBundle(“user”);

ResourceBundle中常用方法:
```java
String getString(String key) : 通过键,获取对应的值

【2】代码实践

通过ResourceBundle工具类
将一个属性文件 放到src目录中,使用ResourceBundle去获取键值对数据

package com.itheima.resourcebundle_demo;
import java.util.ResourceBundle;
/*
    1   java.util.ResourceBundle : 它是一个抽象类
        我们可以使用它的子类PropertyResourceBundle来读取以.properties结尾的配置文件
    2   static ResourceBundle getBundle(String baseName) 可以根据名字直接获取默认语言环境下的属性资源。
        参数注意: baseName
            1.属性集名称不含扩展名。
            2.属性集文件是在src目录中的
        比如:src中存在一个文件 user.properties
        ResourceBundle bundle = ResourceBundle.getBundle("user");
    3 ResourceBundle中常用方法:
         String getString(String key) : 通过键,获取对应的值
    优点 : 快速读取属性文件的值
     需求 :
        通过ResourceBundle工具类
        将一个属性文件 放到src目录中,使用ResourceBundle去获取键值对数据
 */
public class ResourceBundleDemo {
    public static void main(String[] args) {
        // public static final ResourceBundle getBundle(String baseName)
        // baseName : properties文件的名字 , 注意 : 扩展名不需要加上 , properties必须在src的根目录下
        ResourceBundle resourceBundle = ResourceBundle.getBundle("user");
        // String getString(String key) : 通过键,获取对应的值
        String value1 = resourceBundle.getString("username");
        String value2 = resourceBundle.getString("password");
        System.out.println(value1);
        System.out.println(value2);
    }
}

内容小结

  1. 如果要使用ResourceBundle加载属性文件,属性文件需要放置在哪个位置?

    src的根目录
    
  2. 请描述使用ResourceBundle获取属性值的大致步骤是怎样的?

    1 获取ResourceBundle对象
    2 通过ResourceBundle类中的getString(key) : 根据键找值
    

    8 递归

  • 概述
    • 递归概述:以编程的角度来看,递归指的是方法定义中调用方法本身的现象
  • 好处
    • 把一个复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解
      小的问题解决 , 大的问题也会逐一进行解决
  • 注意
    • 递归出口:否则会出现内存溢出
    • 递归规则:需要找到与原问题相似的规模较小的问题
  • 案例

    package com.itheima.recursion_demo;
    /*
          需求:用递归求5的阶乘,并把结果在控制台输出
          思路:
              1 定义一个方法,用于递归求阶乘,参数为一个int类型的变量
              2 在方法内部判断该变量的值是否是1
                  是:返回1
                  不是:返回n*(n-1)!
              3 调用方法
              4 输出结果
    */
    public class Demo1 {
      public static void main(String[] args) {
          int result = jc(5);
          System.out.println("5的阶乘是:" + result);
      }
      private static int jc(int n) {
          if (n == 1) {
              return 1;
          }
          return n * jc(n - 1);
      }
    }
    
  • 内存分析
    day10 File,IO流,字节流,Properties集合,ResourceBundle工具类,递归 - 图3

    package com.itheima.recursion_demo;
    import java.io.File;
    /*
      需求 : 使用递归删除计算机中指定的文件夹
      删除D盘中的aaa文件夹!
      File类 : delete()可以直接删除文件 或者 空文件夹
      aaa
          --bbb
              --ddd.txt
          --ccc.txt
    */
    public class Demo2 {
      public static void main(String[] args) {
          //删除指定文件夹
          File dir = new File("D:/abc");
          deleteFile(dir);
      }
      /**
       * 删除文件或者文件夹
       *
       * @param file 文件或者文件夹
       */
      public static void deleteFile(File file) {
          if (!file.exists()) {
              //如果文件不存在,抛出一个异常
              throw new RuntimeException("您删除的文件,或者目录不存在!!");
          } else {
              //存在
              if (file.isFile()) {
                  //删除文件
                  boolean result = file.delete();//删除文件
                  System.out.println("删除文件:" + file + "-->" + result);
              } else {
                  //文件夹删除
                  //文件夹删除前,先要把子文件删除
                  //file删除是大问题,子文件删除是小问题
                  File[] files = file.listFiles();
                  for (File child : files) {
                      //删除子文件
                      deleteFile(child);//递归删除子文件
                  }
                  //子文件删除完毕后,删除自身
                  boolean result = file.delete();
                  System.out.println("删除文件夹:" + file + "-->" + result);
              }
          }
      }
    }