1. 文件流

第18章 IO流 - 图3

件在程序中是以流的形式来操作的

: 数据在数据源(文件)和程序(内存)之间经历的路径
输入流 : 数据从数据源(文件)到程序(内存)的路径
输出流 : 数据从程序(内存)到数据源(文件)的路径输出流

2. 常用的文件操作

创建文件对象相关构造器和方法

  1. new File( String pathname)//很根据路径构建一个File对象
  2. new File( File parent, String child)//根据父目录文件+子路径构建
  3. new File( String parent, String child)//根据父目录+子路径构建

举例:

  1. public class FileCreate {
  2. public static void main(String[] args) {
  3. }
  4. //方式1 new File(String pathname)
  5. @Test
  6. public void create01() {
  7. String filePath = "e:\\news1.txt";
  8. File file = new File(filePath);
  9. try {
  10. file.createNewFile();
  11. System.out.println("文件创建成功");
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. //方式2 new File(File parent,String child) //根据父目录文件+子路径构建
  17. //e:\\news2.txt
  18. @Test
  19. public void create02() {
  20. File parentFile = new File("e:\\");
  21. String fileName = "news2.txt";
  22. //这里的file对象,在java程序中,只是一个对象
  23. //只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
  24. File file = new File(parentFile, fileName);
  25. try {
  26. file.createNewFile();
  27. System.out.println("创建成功~");
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. //方式3 new File(String parent,String child) //根据父目录+子路径构建
  33. @Test
  34. public void create03() {
  35. //String parentPath = "e:\\";
  36. String parentPath = "e:\\";
  37. String fileName = "news4.txt";
  38. File file = new File(parentPath, fileName);
  39. try {
  40. file.createNewFile();
  41. System.out.println("创建成功~");
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }

获取文件相关信息

第18章 IO流 - 图4

第18章 IO流 - 图5

  1. public void info() {
  2. //先创建文件对象
  3. File file = new File("e:\\news1.txt");
  4. //调用相应的方法,得到对应信息
  5. System.out.println("文件名字=" + file.getName());
  6. //getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
  7. System.out.println("文件绝对路径=" + file.getAbsolutePath());
  8. System.out.println("文件父级目录=" + file.getParent());
  9. System.out.println("文件大小(字节)=" + file.length()); //UTF-8一个英文对应一个字节 一个中文对应3个字节
  10. System.out.println("文件是否存在=" + file.exists());//T
  11. System.out.println("是不是一个文件=" + file.isFile());//T
  12. System.out.println("是不是一个目录=" + file.isDirectory());//F 目录就是文件夹
  13. }

目录的操作和文件的删除

第18章 IO流 - 图6

应用案例演示

第18章 IO流 - 图7

  1. @Test
  2. public void m1() {
  3. String filePath = "e:\\news1.txt";
  4. File file = new File(filePath);
  5. if (file.exists()) {
  6. if (file.delete()) {
  7. System.out.println(filePath + "删除成功");
  8. } else {
  9. System.out.println(filePath + "删除失败");
  10. }
  11. } else {
  12. System.out.println("该文件不存在...");
  13. }
  14. }
  15. //判断 D:\\demo02 是否存在,存在就删除,否则提示不存在
  16. //这里我们需要体会到,在java编程中,目录也被当做文件
  17. @Test
  18. public void m2() {
  19. String filePath = "D:\\demo02";
  20. File file = new File(filePath);
  21. if (file.exists()) {
  22. if (file.delete()) {
  23. System.out.println(filePath + "删除成功");
  24. } else {
  25. System.out.println(filePath + "删除失败");
  26. }
  27. } else {
  28. System.out.println("该目录不存在...");
  29. }
  30. }
  31. //判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
  32. @Test
  33. public void m3() {
  34. String directoryPath = "D:\\demo\\a\\b\\c";
  35. File file = new File(directoryPath);
  36. if (file.exists()) {
  37. System.out.println(directoryPath + "存在..");
  38. } else {
  39. if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()
  40. System.out.println(directoryPath + "创建成功..");
  41. } else {
  42. System.out.println(directoryPath + "创建失败...");
  43. }
  44. }
  45. }

3. IO 流原理及流的分类

Java IO 流原理

  1. I/O是Input/ Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写文件,网络通讯等

  2. Java程序中,对于数据的输入/输出操作以”流(stream)”的方式进行

  3. Java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

  4. 输入 input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中

  5. 输出 output:将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类

按操作数据单位不同分为 : 字节流 (8bit) [二进制文件] , 字符流 (按字符) [文本文件]
按数据流的流向不同分为 : 输入流 , 输出流
按流的角色的不同分为 : 节点流 ,处理流/包装流

下面四个都是抽象类():

(抽象基类〕 字节流 字符流
输入流 Inputstream Reader
输出流 Outputstream Writer
  1. Java的i/o流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀

4. IO 流体系图-常用的类

IO 流体系图

第18章 IO流 - 图8

文件 VS 流

第18章 IO流 - 图9

5. 常用类 节点流

常用类

InputStream:字节输入流
Inputstream 抽象类是所有类字节输入流的超类
InputStream 常用的子类

  1. Filelnputstream : 文件输入流

  2. BufferedInputstrea : 缓冲字节输入流

  3. ObjectInputStream : 对象字节输入流

5.1 FileCopy 文件拷贝

  1. public class FileCopy {
  2. public static void main(String[] args) {
  3. //完成 文件拷贝,将 e:\\Koala.jpg 拷贝 c:\\
  4. //思路分析
  5. //1. 创建文件的输入流 , 将文件读入到程序
  6. //2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.
  7. String srcFilePath = "e:\\Koala.jpg";
  8. String destFilePath = "e:\\Koala3.jpg";
  9. FileInputStream fileInputStream = null;
  10. FileOutputStream fileOutputStream = null;
  11. try {
  12. fileInputStream = new FileInputStream(srcFilePath);
  13. fileOutputStream = new FileOutputStream(destFilePath);
  14. //定义一个字节数组,提高读取效果
  15. byte[] buf = new byte[1024];
  16. int readLen = 0;
  17. while ((readLen = fileInputStream.read(buf)) != -1) {
  18. //读取到后,就写入到文件 通过 fileOutputStream
  19. //即,是一边读,一边写
  20. fileOutputStream.write(buf, 0, readLen);//一定要使用这个方法
  21. }
  22. System.out.println("拷贝ok~");
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. } finally {
  26. try {
  27. //关闭输入流和输出流,释放资源
  28. if (fileInputStream != null) {
  29. fileInputStream.close();
  30. }
  31. if (fileOutputStream != null) {
  32. fileOutputStream.close();
  33. }
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39. }

tips : 读取一部分文件,就拷贝一部分文件,循环操作

5.2 FileInputStream 字节输入流

第18章 IO流 - 图10

第18章 IO流 - 图11

方案一:

  1. @Test
  2. public void readFile01() {
  3. String filePath = "e:\\hello.txt";
  4. int readData = 0;
  5. FileInputStream fileInputStream = null;
  6. try {
  7. //创建 FileInputStream 对象,用于读取 文件
  8. fileInputStream = new FileInputStream(filePath);
  9. //从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
  10. //如果返回-1 , 表示读取完毕
  11. while ((readData = fileInputStream.read()) != -1) {
  12. System.out.print((char)readData);//转成char显示
  13. }
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. } finally {
  17. //关闭文件流,释放资源.
  18. try {
  19. fileInputStream.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }

方案二:

  1. 使用 read(byte[] b) 读取文件,提高效率
  2. //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
  3. //如果返回-1 , 表示读取完毕
  4. //如果读取正常, 返回实际读取的字节数
  1. @Test
  2. public void readFile02() {
  3. String filePath = "e:\\hello.txt";
  4. //字节数组
  5. byte[] buf = new byte[8]; //一次读取8个字节.
  6. int readLen = 0;
  7. FileInputStream fileInputStream = null;
  8. try {
  9. //创建 FileInputStream 对象,用于读取 文件
  10. fileInputStream = new FileInputStream(filePath);
  11. //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
  12. //如果返回-1 , 表示读取完毕
  13. //如果读取正常, 返回实际读取的字节数
  14. while ((readLen = fileInputStream.read(buf)) != -1) {
  15. System.out.print(new String(buf, 0, readLen));//显示
  16. }
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. } finally {
  20. //关闭文件流,释放资源.
  21. try {
  22. fileInputStream.close();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

5.3 FileOutputStream 字节输出流

第18章 IO流 - 图12

第18章 IO流 - 图13

  1. @Test
  2. public void writeFile() {
  3. //创建 FileOutputStream对象
  4. String filePath = "e:\\a.txt";
  5. FileOutputStream fileOutputStream = null;
  6. try {
  7. //得到 FileOutputStream对象 对象
  8. //老师说明
  9. //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
  10. //2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
  11. fileOutputStream = new FileOutputStream(filePath, true);
  12. //写入一个字节
  13. //fileOutputStream.write('H');//
  14. //写入字符串
  15. String str = "hsp,world!";
  16. //str.getBytes() 可以把 字符串-> 字节数组
  17. //fileOutputStream.write(str.getBytes());
  18. /*
  19. write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
  20. */
  21. fileOutputStream.write(str.getBytes(), 0, 3);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } finally {
  25. try {
  26. fileOutputStream.close();
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

str.getBytes() 可以把 字符串-> 字节数组

5.4 FileReader 字符串输入流

第18章 IO流 - 图14

FileReader 相关方法:

第18章 IO流 - 图15

单个字符读取文件

  1. @Test
  2. public void readFile01() {
  3. String filePath = "e:\\story.txt";
  4. FileReader fileReader = null;
  5. int data = 0;
  6. //1. 创建FileReader对象
  7. try {
  8. fileReader = new FileReader(filePath);
  9. //循环读取 使用read, 单个字符读取
  10. while ((data = fileReader.read()) != -1) {
  11. System.out.print((char) data);
  12. }
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. } finally {
  16. try {
  17. if (fileReader != null) {
  18. fileReader.close();
  19. }
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }

字符数组读取文件

  1. @Test
  2. public void readFile02() {
  3. System.out.println("~~~readFile02 ~~~");
  4. String filePath = "e:\\story.txt";
  5. FileReader fileReader = null;
  6. int readLen = 0;
  7. char[] buf = new char[8];
  8. //1. 创建FileReader对象
  9. try {
  10. fileReader = new FileReader(filePath);
  11. //循环读取 使用read(buf), 返回的是实际读取到的字符数
  12. //如果返回-1, 说明到文件结束
  13. while ((readLen = fileReader.read(buf)) != -1) {
  14. System.out.print(new String(buf, 0, readLen));
  15. }
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } finally {
  19. try {
  20. if (fileReader != null) {
  21. fileReader.close();
  22. }
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

5.5 FileWriter 字符输入流

第18章 IO流 - 图16 FileWriter 常用方法

第18章 IO流 - 图17

TIPS : FileWriter使用后,必须要关闭(close)或者刷新(flush),否则写入不到指定文件,会保存在内存中.

  1. public class FileWriter_ {
  2. public static void main(String[] args) {
  3. String filePath = "e:\\note.txt";
  4. //创建FileWriter对象
  5. FileWriter fileWriter = null;
  6. char[] chars = {'a', 'b', 'c'};
  7. try {
  8. fileWriter = new FileWriter(filePath);//默认是覆盖写入
  9. // 3) write(int):写入单个字符
  10. fileWriter.write('H');
  11. // 4) write(char[]):写入指定数组
  12. fileWriter.write(chars);
  13. // 5) write(char[],off,len):写入指定数组的指定部分
  14. fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
  15. // 6) write(string):写入整个字符串
  16. fileWriter.write(" 你好北京~");
  17. fileWriter.write("风雨之后,定见彩虹");
  18. // 7) write(string,off,len):写入字符串的指定部分
  19. fileWriter.write("上海天津", 0, 2);
  20. //在数据量大的情况下,可以使用循环操作.
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. } finally {
  24. //对应FileWriter , 一定要关闭流,或者flush才能真正的把数据写入到文件
  25. //老韩看源码就知道原因.
  26. /*
  27. 看看代码
  28. private void writeBytes() throws IOException {
  29. this.bb.flip();
  30. int var1 = this.bb.limit();
  31. int var2 = this.bb.position();
  32. assert var2 <= var1;
  33. int var3 = var2 <= var1 ? var1 - var2 : 0;
  34. if (var3 > 0) {
  35. if (this.ch != null) {
  36. assert this.ch.write(this.bb) == var3 : var3;
  37. } else {
  38. this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
  39. }
  40. }
  41. this.bb.clear();
  42. }
  43. */
  44. try {
  45. //fileWriter.flush();
  46. //关闭文件流,等价 flush() + 关闭
  47. fileWriter.close();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. System.out.println("程序结束...");
  53. }
  54. }

6. 节点流和处理流

基本介绍

第18章 IO流 - 图18

节点流和处理流一览图

第18章 IO流 - 图19

节点流和处理流的区别和联系

第18章 IO流 - 图20

处理流的功能主要体现在以下两个方面:

  1. 性能的提高:主要以增加缓冲的方式来提高输入输岀的效率
  2. 操作的便捷:处理流可能提供了一系列便捷的方法来一次输λ输岀大批量的数据,使用更加灵活方便

7. 包装类 处理流

7.1 标准输入输出流

类型 默认设备
System.in 标准输入 InputStream 键盘
System.out 标准输出 PrintStream 显示器
  1. public class InputAndOutput {
  2. public static void main(String[] args) {
  3. //System 类 的 public final static InputStream in = null;
  4. // System.in 编译类型 InputStream
  5. // System.in 运行类型 BufferedInputStream
  6. // 表示的是标准输入 键盘
  7. System.out.println(System.in.getClass());
  8. //老韩解读
  9. //1. System.out public final static PrintStream out = null;
  10. //2. 编译类型 PrintStream
  11. //3. 运行类型 PrintStream
  12. //4. 表示标准输出 显示器
  13. System.out.println(System.out.getClass());
  14. System.out.println("hello, 韩顺平教育~");
  15. Scanner scanner = new Scanner(System.in);
  16. System.out.println("输入内容");
  17. String next = scanner.next();
  18. System.out.println("next=" + next);
  19. }
  20. }

第18章 IO流 - 图21

第18章 IO流 - 图22

7.2 打印流-PrintStream 和 PrintWriter

打印流只有输出流没有输入流

PrintStream

第18章 IO流 - 图23

  1. public class PrintStream_ {
  2. public static void main(String[] args) throws IOException {
  3. PrintStream out = System.out;
  4. //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
  5. /*
  6. public void print(String s) {
  7. if (s == null) {
  8. s = "null";
  9. }
  10. write(s);
  11. }
  12. */
  13. out.print("john, hello");
  14. //因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出
  15. out.write("韩顺平,你好".getBytes());
  16. out.close();
  17. //我们可以去修改打印流输出的位置/设备
  18. //1. 输出修改成到 "e:\\f1.txt"
  19. //2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt
  20. //3. public static void setOut(PrintStream out) {
  21. // checkIO();
  22. // setOut0(out); // native 方法,修改了out
  23. // }
  24. System.setOut(new PrintStream("e:\\f1.txt"));
  25. System.out.println("hello, 韩顺平教育~");
  26. }
  27. }

PrintWriter第18章 IO流 - 图24

  1. public class PrintWriter_ {
  2. public static void main(String[] args) throws IOException {
  3. //PrintWriter printWriter = new PrintWriter(System.out);
  4. PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
  5. printWriter.print("hi, 北京你好~~~~");
  6. printWriter.close();//flush + 关闭流, 才会将数据写入到文件..
  7. }
  8. }

tips : flush + 关闭流, 才会将数据写入到文件..

7.3 对象流-ObjectInputStream 和 ObjectOutputStream

第18章 IO流 - 图25

序列化和反序列化

  1. 序列化就是在保存数据时,保存数据的值数据类型
  2. 反序列化就是在恢复数据时,恢复数据的值数据类型
  3. 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:

    • Serializable : 这是一个标记接口,没有方法
    • Externalizable : 该接口有方法需要实现,因此我们一般实现上面的 Serializable接口

第18章 IO流 - 图26

对象流介绍

功能:提供了对基本类型或对象类型的序列化和反序列化的方法

ObjectOutputStream 提供 序列化功能

ObjectInputStream 提供 反序列化功能

ObjectOutputStream 对象输出流

第18章 IO流 - 图27

  1. public class ObjectOutStream_ {
  2. public static void main(String[] args) throws Exception {
  3. //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
  4. String filePath = "e:\\data.dat";
  5. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
  6. //序列化数据到 e:\data.dat
  7. oos.writeInt(100);// int -> Integer (实现了 Serializable)
  8. oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
  9. oos.writeChar('a');// char -> Character (实现了 Serializable)
  10. oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
  11. oos.writeUTF("韩顺平教育");//String
  12. //保存一个dog对象
  13. oos.writeObject(new Dog("旺财", 10, "日本", "白色"));
  14. oos.close();
  15. System.out.println("数据保存完毕(序列化形式)");
  16. }
  17. }

ObjectInputStream 对象输入流

第18章 IO流 - 图28

  1. public class ObjectInputStream_ {
  2. public static void main(String[] args) throws IOException, ClassNotFoundException {
  3. //指定反序列化的文件
  4. String filePath = "e:\\data.dat";
  5. ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
  6. //读取
  7. //老师解读
  8. //1. 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
  9. //2. 否则会出现异常
  10. System.out.println(ois.readInt());
  11. System.out.println(ois.readBoolean());
  12. System.out.println(ois.readChar());
  13. System.out.println(ois.readDouble());
  14. System.out.println(ois.readUTF());
  15. //dog 的编译类型是 Object , dog 的运行类型是 Dog
  16. Object dog = ois.readObject();
  17. System.out.println("运行类型=" + dog.getClass());
  18. System.out.println("dog信息=" + dog);//底层 Object -> Dog
  19. //这里是特别重要的细节:
  20. //1. 如果我们希望调用Dog的方法, 需要向下转型
  21. //2. 需要我们将Dog类的定义,放在到可以引用的位置
  22. Dog dog2 = (Dog)dog;
  23. System.out.println(dog2.getName()); //旺财..
  24. //关闭流, 关闭外层流即可,底层会关闭 FileInputStream 流
  25. ois.close();
  26. }
  27. }

注意事项和细节说明

  1. 读写顺序要一致
  2. 要求序列化或反序列化对象,需要实现 Serializable
  3. 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
  4. 序列化对象时,默认将里面所有属低都进行序列化,但除了static或transient修饰的成员
  5. 序列化对象时,要求里面属性的类型也需要实现序列化接口
  6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化

7.4 转换流-InputStreamReader 和 OutputStreamWriter

  1. InputStreamReader: Reader的子类,可以将 Inputstream(字节流)包装/转换成 Reader(字符流)
  2. OutputStreamWriter: Writer的子类,实现将 OutputStream(字节流)包装/转换成 Writer(字符流)
  3. 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
  4. 可以在使用时指定编码格式(比如utf-8,gbk,gb2312,lso8859-1等)

InputStreamReader 字节->字符 输入转换流

第18章 IO流 - 图29

tips : 可以传入一个InputStream对象,一个编码方式

  1. public class InputStreamReader_ {
  2. public static void main(String[] args) throws IOException {
  3. String filePath = "e:\\a.txt";
  4. //解读
  5. //1. 把 FileInputStream 转成 InputStreamReader
  6. //2. 指定编码 gbk
  7. //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
  8. //3. 把 InputStreamReader 传入 BufferedReader
  9. //BufferedReader br = new BufferedReader(isr);
  10. //将2 和 3 合在一起
  11. BufferedReader br = new BufferedReader(new InputStreamReader(
  12. new FileInputStream(filePath), "gbk"));
  13. //4. 读取
  14. String s = br.readLine();
  15. System.out.println("读取内容=" + s);
  16. //5. 关闭外层流
  17. br.close();
  18. }
  19. }

OutputStreamWriter 字节->字符 输出转换流

第18章 IO流 - 图30

实例

第18章 IO流 - 图31

  1. public class OutputStreamWriter_ {
  2. public static void main(String[] args) throws IOException {
  3. String filePath = "e:\\hsp.txt";
  4. String charSet = "utf-8";
  5. OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
  6. osw.write("hi, 韩顺平教育");
  7. osw.close();
  8. System.out.println("按照 " + charSet + " 保存文件成功~");
  9. }
  10. }

7.5 处理流-BufferedReader 和 BufferedWriter

  1. Buffered Reader和 Bufferedwriter属于字符流,是按照字符来读取数据的
  2. 关闭时处理流,只需要关闭外层流即可

BufferedReader 字符型读取包装流

第18章 IO流 - 图32

  1. public class BufferedReader_ extends Reader_{
  2. private Reader_ reader_; //属性是 Reader_类型
  3. //接收Reader_ 子类对象
  4. public BufferedReader_(Reader_ reader_) {
  5. this.reader_ = reader_;
  6. }
  7. public void readFile() { //封装一层
  8. reader_.readFile();
  9. }
  10. //让方法更加灵活, 多次读取文件, 或者加缓冲byte[] ....
  11. public void readFiles(int num) {
  12. for(int i = 0; i < num; i++) {
  13. reader_.readFile();
  14. }
  15. }
  16. //扩展 readString, 批量处理字符串数据
  17. public void readStrings(int num) {
  18. for(int i = 0; i <num; i++) {
  19. reader_.readString();
  20. }
  21. }
  22. }

BufferedWriter 字符型写入包装流

第18章 IO流 - 图33

  1. public class BufferedReader_ {
  2. public static void main(String[] args) throws Exception {
  3. String filePath = "e:\\a.java";
  4. //创建bufferedReader
  5. BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
  6. //读取
  7. String line; //按行读取, 效率高
  8. //说明
  9. //1. bufferedReader.readLine() 是按行读取文件
  10. //2. 当返回null 时,表示文件读取完毕
  11. while ((line = bufferedReader.readLine()) != null) {
  12. System.out.println(line);
  13. }
  14. //关闭流, 这里注意,只需要关闭 BufferedReader ,因为底层会自动的去关闭 节点流
  15. //FileReader。
  16. /*
  17. public void close() throws IOException {
  18. synchronized (lock) {
  19. if (in == null)
  20. return;
  21. try {
  22. in.close();//in 就是我们传入的 new FileReader(filePath), 关闭了.
  23. } finally {
  24. in = null;
  25. cb = null;
  26. }
  27. }
  28. }
  29. */
  30. bufferedReader.close();
  31. }
  32. }

BufferedCopy

第18章 IO流 - 图34

  1. public class BufferedCopy_ {
  2. public static void main(String[] args) {
  3. //老韩说明
  4. //1. BufferedReader 和 BufferedWriter 是安装字符操作
  5. //2. 不要去操作 二进制文件[声音,视频,doc, pdf ], 可能造成文件损坏
  6. //BufferedInputStream
  7. //BufferedOutputStream
  8. String srcFilePath = "e:\\a.java";
  9. String destFilePath = "e:\\a2.java";
  10. // String srcFilePath = "e:\\0245_韩顺平零基础学Java_引出this.avi";
  11. // String destFilePath = "e:\\a2韩顺平.avi";
  12. BufferedReader br = null;
  13. BufferedWriter bw = null;
  14. String line;
  15. try {
  16. br = new BufferedReader(new FileReader(srcFilePath));
  17. bw = new BufferedWriter(new FileWriter(destFilePath));
  18. //说明: readLine 读取一行内容,但是没有换行
  19. while ((line = br.readLine()) != null) {
  20. //每读取一行,就写入
  21. bw.write(line);
  22. //插入一个换行
  23. bw.newLine();
  24. }
  25. System.out.println("拷贝完毕...");
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. } finally {
  29. //关闭流
  30. try {
  31. if(br != null) {
  32. br.close();
  33. }
  34. if(bw != null) {
  35. bw.close();
  36. }
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  42. }

7.6 处理流-BufferedInputStream 和 BufferedOutputStream

BufferedInputStream 字节型输入包装流

第18章 IO流 - 图35

第18章 IO流 - 图36

BufferedOutputStream 字节型输出包装流

第18章 IO流 - 图37

第18章 IO流 - 图38

BufferedCopy

第18章 IO流 - 图39

  1. public class BufferedCopy02 {
  2. public static void main(String[] args) {
  3. // String srcFilePath = "e:\\Koala.jpg";
  4. // String destFilePath = "e:\\hsp.jpg";
  5. // String srcFilePath = "e:\\0245_韩顺平零基础学Java_引出this.avi";
  6. // String destFilePath = "e:\\hsp.avi";
  7. String srcFilePath = "e:\\a.java";
  8. String destFilePath = "e:\\a3.java";
  9. //创建BufferedOutputStream对象BufferedInputStream对象
  10. BufferedInputStream bis = null;
  11. BufferedOutputStream bos = null;
  12. try {
  13. //因为 FileInputStream 是 InputStream 子类
  14. bis = new BufferedInputStream(new FileInputStream(srcFilePath));
  15. bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
  16. //循环的读取文件,并写入到 destFilePath
  17. byte[] buff = new byte[1024];
  18. int readLen = 0;
  19. //当返回 -1 时,就表示文件读取完毕
  20. while ((readLen = bis.read(buff)) != -1) {
  21. bos.write(buff, 0, readLen);
  22. }
  23. System.out.println("文件拷贝完毕~~~");
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. } finally {
  27. //关闭流 , 关闭外层的处理流即可,底层会去关闭节点流
  28. try {
  29. if(bis != null) {
  30. bis.close();
  31. }
  32. if(bos != null) {
  33. bos.close();
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40. }

8. Properties类

第18章 IO流 - 图40

  1. public class Properties01 {
  2. public static void main(String[] args) throws IOException {
  3. //读取mysql.properties 文件,并得到ip, user 和 pwd
  4. BufferedReader br = new BufferedReader(new FileReader("chapter19\\src\\mysql.properties"));
  5. String line = "";
  6. while ((line = br.readLine()) != null) { //循环读取
  7. String[] split = line.split("=");
  8. //如果我们要求指定的ip值
  9. if("ip".equals(split[0])) {
  10. System.out.println(split[0] + "值是: " + split[1]);
  11. }
  12. }
  13. br.close();
  14. }
  15. }

基本介绍

  1. 专门用于读写配置文件的集合类
    配置文件的格式: 键=值

  2. 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是 String

  3. Properties的常见方法

  • load : 加载配置文件的键值对到 Properties对象

  • list : 将数据显示到指定设备

  • getProperty(key) : 根据键获取值

    • proporties.getProperty(key)
  • setProperty(key, value) : 设置键值对到 Properties对象

  • store : 将 Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为 unicode 码

应用案例

第18章 IO流 - 图41

  1. public class Properties02 {
  2. public static void main(String[] args) throws IOException {
  3. //使用Properties 类来读取mysql.properties 文件
  4. //1. 创建Properties 对象
  5. Properties properties = new Properties();
  6. //2. 加载指定配置文件
  7. properties.load(new FileReader("src\\mysql.properties"));
  8. //3. 把k-v显示控制台
  9. properties.list(System.out);
  10. //4. 根据key 获取对应的值
  11. String user = properties.getProperty("user");
  12. String pwd = properties.getProperty("pwd");
  13. System.out.println("用户名=" + user);
  14. System.out.println("密码是=" + pwd);
  15. }
  16. }

第18章 IO流 - 图42

  1. public class Properties01 {
  2. public static void main(String[] args) throws IOException {
  3. //读取mysql.properties 文件,并得到ip, user 和 pwd
  4. BufferedReader br = new BufferedReader(new FileReader("chapter19\\src\\mysql.properties"));
  5. String line = "";
  6. while ((line = br.readLine()) != null) { //循环读取
  7. String[] split = line.split("=");
  8. //如果我们要求指定的ip值
  9. if("ip".equals(split[0])) {
  10. System.out.println(split[0] + "值是: " + split[1]);
  11. }
  12. }
  13. br.close();
  14. }
  15. }

基本介绍

  1. 专门用于读写配置文件的集合类
    配置文件的格式: 键=值

  2. 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是 String

  3. Properties的常见方法

  • load : 加载配置文件的键值对到 Properties对象

  • list : 将数据显示到指定设备

  • getProperty(key) : 根据键获取值

    • proporties.getProperty(key)
  • setProperty(key, value) : 设置键值对到 Properties对象

  • store : 将 Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为 unicode 码

应用案例

第18章 IO流 - 图43

  1. public class Properties02 {
  2. public static void main(String[] args) throws IOException {
  3. //使用Properties 类来读取mysql.properties 文件
  4. //1. 创建Properties 对象
  5. Properties properties = new Properties();
  6. //2. 加载指定配置文件
  7. properties.load(new FileReader("src\\mysql.properties"));
  8. //3. 把k-v显示控制台
  9. properties.list(System.out);
  10. //4. 根据key 获取对应的值
  11. String user = properties.getProperty("user");
  12. String pwd = properties.getProperty("pwd");
  13. System.out.println("用户名=" + user);
  14. System.out.println("密码是=" + pwd);
  15. }
  16. }
  1. public class Properties03 {
  2. public static void main(String[] args) throws IOException {
  3. //使用Properties 类来创建 配置文件, 修改配置文件内容
  4. Properties properties = new Properties();
  5. //创建
  6. //1.如果该文件没有key 就是创建
  7. //2.如果该文件有key ,就是修改
  8. /*
  9. Properties 父类是 Hashtable , 底层就是Hashtable 核心方法
  10. public synchronized V put(K key, V value) {
  11. // Make sure the value is not null
  12. if (value == null) {
  13. throw new NullPointerException();
  14. }
  15. // Makes sure the key is not already in the hashtable.
  16. Entry<?,?> tab[] = table;
  17. int hash = key.hashCode();
  18. int index = (hash & 0x7FFFFFFF) % tab.length;
  19. @SuppressWarnings("unchecked")
  20. Entry<K,V> entry = (Entry<K,V>)tab[index];
  21. for(; entry != null ; entry = entry.next) {
  22. if ((entry.hash == hash) && entry.key.equals(key)) {
  23. V old = entry.value;
  24. entry.value = value;//如果key 存在,就替换
  25. return old;
  26. }
  27. }
  28. addEntry(hash, key, value, index);//如果是新k, 就addEntry
  29. return null;
  30. }
  31. */
  32. properties.setProperty("charset", "utf8");
  33. properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode码值
  34. properties.setProperty("pwd", "888888");
  35. //将k-v 存储文件中即可
  36. properties.store(new FileOutputStream("src\\mysql2.properties"), null);
  37. System.out.println("保存配置文件成功~");
  38. }
  39. }

9. 本章作业

第18章 IO流 - 图44

  1. public class Homework01 {
  2. public static void main(String[] args) throws IOException {
  3. /**
  4. *(1) 在判断D盘下是否有文件夹mytemp ,如果没有就创建mytemp
  5. *(2) 在e:\\mytemp 目录下, 创建文件 hello.txt
  6. *(3) 如果hello.txt 已经存在,提示该文件已经存在,就不要再重复创建了
  7. *(4) 并且在hello.txt 文件中,写入 hello,world~
  8. */
  9. String directoryFile = "D:\\mytemp";
  10. File file = new File(directoryFile);
  11. if (!file.exists()){
  12. file.mkdir();
  13. System.out.println(directoryFile + "创建成功");
  14. }else {
  15. System.out.println(directoryFile + "已经存在");
  16. }
  17. String filepath = directoryFile + "\\hello.txt";
  18. file = new File(filepath);
  19. if (!file.exists()){
  20. if (file.createNewFile()) {
  21. System.out.println("文件创建成功");
  22. BufferedWriter bw = new BufferedWriter(new FileWriter(filepath));
  23. bw.write("hello,world~");
  24. bw.close();
  25. }else{
  26. System.out.println("文件创建失败");
  27. }
  28. }else{
  29. System.out.println("文件已经存在");
  30. }
  31. }
  32. }

第18章 IO流 - 图45

  1. public class Homework02 {
  2. public static void main(String[] args) throws IOException {
  3. /**
  4. * 要求: 使用BufferedReader读取一个文本文件,为每行加上行号,
  5. * 再连同内容一并输出到屏幕上。
  6. */
  7. String line = null;
  8. int lineNum = 0;
  9. String filePath = "D:\\hello.txt";
  10. File file = new File(filePath);
  11. // FileInputStream fis = new FileInputStream(file);
  12. // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis,"gbk"));
  13. // InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),"gbk");
  14. // BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  15. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));
  16. while((line = bufferedReader.readLine()) != null) {
  17. System.out.println(++lineNum + " " + line);
  18. }
  19. bufferedReader.close();
  20. }
  21. }

第18章 IO流 - 图46

  1. public class Homework03 {
  2. public static void main(String[] args) throws IOException {
  3. /**
  4. * (1) 要编写一个dog.properties name=tom age=5 color=red
  5. * (2) 编写Dog 类(name,age,color) 创建一个dog对象,读取dog.properties 用相应的内容完成属性初始化, 并输出
  6. * (3) 将创建的Dog 对象 ,序列化到 文件 e:\\dog.dat 文件
  7. */
  8. String filePath = "chapter19\\src\\dog.properties";
  9. Properties properties = new Properties();
  10. properties.load(new FileReader(filePath));
  11. String name = properties.getProperty("name");//需要将Object类型转型为String类型
  12. int age = Integer.parseInt(properties.getProperty("age")); //需要将Object类型转型为String类型
  13. String color = properties.getProperty("color"); //需要将Object类型转型为String类型
  14. Dog dog = new Dog(name, age, color);
  15. System.out.println(dog);
  16. String srcFilePath = "D:\\hello.txt";
  17. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(srcFilePath));
  18. oos.writeObject(dog);
  19. oos.close();
  20. System.out.println("序列化完成~");
  21. }
  22. @Test
  23. public void m1() throws IOException, ClassNotFoundException {
  24. String path = "D:\\hello.txt";
  25. ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
  26. Dog dog = (Dog) ois.readObject();
  27. System.out.println("反序列化后~");
  28. System.out.println(dog);
  29. ois.close();
  30. }
  31. }
  32. class Dog implements Serializable {
  33. private String name;
  34. private int age;
  35. private String color;
  36. public Dog(String name, int age, String color) {
  37. this.name = name;
  38. this.age = age;
  39. this.color = color;
  40. }
  41. @Override
  42. public String toString() {
  43. return "Dog{" +
  44. "name='" + name + '\'' +
  45. ", age=" + age +
  46. ", color='" + color + '\'' +
  47. '}';
  48. }
  49. }

10. flush 和 close

l 在java开发中,有时我们会进行流的操作,所以可能会经常遇到这样一段代码

out.flush();

out.close();

有时我们只是大概看懂这些,却不知道其中的原理性东西,下面就来理解一下:

flush()这个函数是清空的意思,用于清空缓冲区的数据流,进行流的操作时,数据先被读到内存中,然后再用数据写到文件中,那么当你数据读完时,我们如果这时调用close()方法关闭读写流,这时就可能造成数据丢失,为什么呢,因为,读入数据完成时不代表写入数据完成,一部分数据可能会留在缓存区中,为了理解这个问题,我们举一个例子:

比如,在农村,几乎每家都有抽水机,抽水机的作用是什么呢,就是把水井里的水抽到水缸中,这时我们就会用水管连接抽水机和水缸(水管就好比是缓冲区),当我们想把水井中的水都抽到水缸中时,我们就让抽水机工作抽水,如果我们发现水井里的水刚好抽完时,我们就会关掉抽水机的开关停止抽水,那么这时,管道里就会遗留一部分水,抽水就是读数据,水缸进水就是写数据,水管充当缓存区的角色,不知道这样是不是具象化了呢

那么这样一来我们如果中途调用close()方法,输出区也还是有数据的,就像水缸里有水,只是在缓冲区遗留了一部分,这时如果我们先调用flush()方法,就会强制把数据输出,缓存区就清空了,最后再关闭读写流调用close()就完成了。

  1. public class PrintWriter extends Writer {
  2. protected Writer out;
  3. /** Checks to make sure that the stream has not been closed */
  4. private void ensureOpen() throws IOException {
  5. if (out == null)
  6. throw new IOException("Stream closed");
  7. }
  8. /**
  9. \* Flushes the stream.
  10. \* @see #checkError()
  11. */
  12. public void flush() {
  13. try {
  14. synchronized (lock) {
  15. ensureOpen();
  16. out.flush();
  17. }
  18. }
  19. catch (IOException x) {
  20. trouble = true;
  21. }
  22. }
  23. }

这是JDK中PrintWriter类提供的flush方法,如上面注释所说,ensureOpen()方法是用于确保该流没有被关闭,如果没有关闭则执行flush方法中的out.flush();