Java IO study notes

1. The core classes
  • File File Class
  • InputStream input stream of bytes
  • Byte output stream OutputStream
  • Reader input character stream
  • Writer character-output stream
  • Closeable shut down stream interface
  • Flushable refresh stream interface
  • Serialization Serializable Interface


2. Flow Classification
  • Input streams: a data source to the program (InputStream, Reader read in)
  • Output streams: the program to the destination (OutputStream, Writer write into)
  • Node Stream: can read and write data directly from a data source or destination
  • Process Flow: not directly connected to the data source or destination, other stream encapsulation. The main object is to simplify and improve the operating performance
  • Node flow and processing flow of the relationship:
    • The first line, the operation of all nodes in the flow IO operations they must be used
    • Process streams to other streams may be processed (operation efficiency or flexibility)
  • Byte stream: read data (InputStream, OutputStream) in bytes
  • Character stream: data read by a character (Reader, Writer), because the coding of different files, so that a character stream object with the efficient operation of the character.
    • Principle: bottom or byte-operation, automatically searches the specified code table

image

image

3.File common API and file encoding

Recommended file path notation:

          1.path= “D:/XXX/XXX/XXX.png”;

          2.path=”D:”+File.separator+”java300”+File.separator+”XXX.png”;

API

  • pathSeparator separator path | path separator
  • File (String parent, String child) constructor
  • File(File parent,String child)                           
  • File(String name)
  • getName()                                                    文件名、路径名
  • getPath()
  • getAbsolutePath()
  • getParent
  • exists()                                                       判断状态
  • isFile()
  • isDirectorv()
  • length()                                                     文件长度
  • createNewFile()                                         创建新文件
  • delete()                                                    删除文件
  • mkdir()                                                    创建目录,需要确保上级目录存在,不存在时创建失败
  • mkdirs()                                                   创建目录,当父目录不存在时一同创建
  • list()                                                        下级名称
  • listFiles()                                                  下级File
  • listRoots()                                                根路径



4.IO流读写操作
  • InputStream                字节输入流的父类,数据单位为字节
    • int  read()
    • void  close()
  • OutputStream              字节输出流的父类,数据单位为字节
    • void  write(int)
    • void flush()
    • void close()
  • Reader                        字符输入流的父类,数据单位为字符
    • int  read()
    • void close()
  • Writer                         字符输出流的父类,数据单位为字符
    • void  write(String)
    • void  flush()
    • void  close()


5.代码段

输入流代码演示

  1 package wangyue;
  2 
  3 import java.io.*;
  4 
  5 public class IoStudy02 {
  6     public static void main(String[] args) {
  7         //1.创建源
  8         File file = new File("test");
  9         //2.创建流
 10         InputStream is = null;
 11         try {
 12             is = new FileInputStream(file);
 13             byte[] flush = new byte[30];//缓冲容器
 14             int len;//接收长度
 15             while ((len = is.read(flush)) != -1) {
 16                 String str = new String(flush, 0, len);
 17                 System.out.println(str);
 18             }
 19         } catch (FileNotFoundException e) {
 20             e.printStackTrace();
 21         } catch (IOException e) {
 22             e.printStackTrace();
 23         }finally {
 24             if (is != null) {
 25                 try {
 26                     is.close();
 27                 } catch (IOException e) {
 28                     e.printStackTrace();
 29                 }
 30             }
 31         }
 32     }
 33 }
 34 

输出流代码演示

  1 package wangyue;
  2 
  3 import java.io.*;
  4 
  5 public class IoStudy03 {
  6     public static void main(String[] args) {
  7         //1.创建源
  8         File dest = new File("output.txt");
  9         //2.选择流
 10         OutputStream os = null;
 11         try {
 12             os = new FileOutputStream(dest);
 13             //3.操作
 14             String msg = "向文件中写入一些没什么用的东西";
 15             byte[] datas = msg.getBytes();//字符串--》字节数组  (编码)
 16             os.write(datas, 0, datas.length);
 17             //刷新流,避免有数据存在在缓存中。即使os.close() 也会刷新流,此处也再刷新一次
 18             os.flush();
 19         } catch (FileNotFoundException e) {
 20             e.printStackTrace();
 21         } catch (IOException e) {
 22             e.printStackTrace();
 23         }finally {
 24             if (os != null) {
 25                 try {
 26                     os.close();
 27                 } catch (IOException e) {
 28                     e.printStackTrace();
 29                 }
 30             }
 31         }
 32 
 33     }
 34 }
 35 

文件拷贝

  1 package wangyue;
  2 
  3 import java.io.*;
  4 
  5 public class IoStudy04 {
  6     public static void main(String[] args) {
  7         //1.创建源
  8         File src = new File("C:/Users/86178/Desktop/微信截图_20191006134845.png");
  9         File dest = new File("C:/Users/86178/Desktop/copy.png");
 10         //2.选择流
 11         InputStream is = null;
 12         OutputStream os = null;
 13         try {
 14             is = new FileInputStream(src);
 15             os = new FileOutputStream(dest,false);
 16             //3.操作
 17             byte[] flush = new byte[1024];
 18             int len;
 19             while ((len = is.read(flush)) != -1) {
 20                 os.write(flush, 0, len);
 21             }
 22             //刷新流,避免有数据存在在缓存中。即使os.close() 也会刷新流,此处也再刷新一次
 23             os.flush();
 24         } catch (FileNotFoundException e) {
 25             e.printStackTrace();
 26         } catch (IOException e) {
 27             e.printStackTrace();
 28         }finally {
 29             if (os != null && is != null) {
 30                 //4.关闭资源,先打开的后关闭。注意要分别关闭
 31                 try {
 32                     is.close();
 33                 } catch (IOException e) {
 34                     e.printStackTrace();
 35                 }
 36                 try {
 37                     os.close();
 38                 } catch (IOException e) {
 39                     e.printStackTrace();
 40                 }
 41             }
 42         }
 43 
 44     }
 45 }
 46 
6.字节数组流   ByteArrayInputStream & ByteArrayOutputStream

字节数组流无需关闭,由java虚拟机gc进行回收.

7.IO工具类
  1 package wangyue;
  2 
  3 import java.io.*;
  4 
  5 /**
  6  * 1、封装拷贝
  7  * 2、封装释放资源
  8  */
  9 public class FileUtils {
 10 
 11     public static void main(String[] args) {
 12 
 13         byte[] datas = null;
 14         //文件到文件
 15         try {
 16             InputStream is = new FileInputStream("test");
 17             OutputStream os = new FileOutputStream("test-copy.txt");
 18             copy(is, os);
 19         } catch (IOException e) {
 20             e.printStackTrace();
 21         }
 22         //文件到字节数组
 23         try {
 24             InputStream is = new FileInputStream("test.png");
 25             ByteArrayOutputStream os = new ByteArrayOutputStream();
 26             copy(is, os);
 27             datas = os.toByteArray();
 28             System.out.println(datas.length);
 29         } catch (IOException e) {
 30             e.printStackTrace();
 31         }
 32         //字节数组到文件
 33         try {
 34             InputStream is = new ByteArrayInputStream(datas);
 35             OutputStream os = new FileOutputStream("test-copy.png");
 36             copy(is,os);
 37         } catch (FileNotFoundException e) {
 38             e.printStackTrace();
 39         }
 40     }
 41 
 42     /**
 43      * 对接输入输出流
 44      * @param is
 45      * @param os
 46      */
 47     public static void copy(InputStream is, OutputStream os) {
 48         try {
 49             byte[] flush = new byte[2014];//缓冲容器
 50             int len;
 51             while ((len = is.read(flush)) != -1) {
 52                 os.write(flush, 0, len);
 53             }
 54             os.flush();
 55         } catch (IOException e) {
 56             e.printStackTrace();
 57         }finally {
 58             close(is,os);
 59         }
 60     }
 61 
 62     /**
 63      * 释放资源
 64      * @param is
 65      * @param os
 66      */
 67     public static void close(InputStream is,OutputStream os) {
 68         try {
 69             if (is != null) {
 70                 is.close();
 71             }
 72         } catch (IOException e) {
 73             e.printStackTrace();
 74         }
 75 
 76         try {
 77             if (os != null) {
 78                 os.close();
 79             }
 80         } catch (IOException e) {
 81             e.printStackTrace();
 82         }
 83     }
 84 
 85     /**
 86      * 释放资源
 87      * @param ios
 88      */
 89     public static void close(Closeable... ios) {
 90         for (Closeable io : ios) {
 91             try {
 92                 if (null != io) {
 93                     io.close();
 94                 }
 95             } catch (IOException e) {
 96                 e.printStackTrace();
 97             }
 98         }
 99     }
100 
101 }
102 
  1 package wangyue;
  2 
  3 import java.io.*;
  4 
  5 public class FileUtils2 {
  6     /**
  7      * 对接输入输出流
  8      * try...with...resource
  9      * 不需要在finally中释放资源,只要try(is,os)即可,系统自动释放资源,不需要关心释放顺序
 10      * @param is
 11      * @param os
 12      */
 13     public static void copy(InputStream is, OutputStream os) {
 14         try (InputStream iss = new FileInputStream("sdf");
 15             OutputStream oss = new FileOutputStream("test")) {
 16 
 17             byte[] flush = new byte[2014];//缓冲容器
 18             int len;
 19             while ((len = is.read(flush)) != -1) {
 20                 os.write(flush, 0, len);
 21             }
 22             os.flush();
 23         } catch (IOException e) {
 24             e.printStackTrace();
 25         }
 26     }
 27 }
 28 


8.装饰器设计模式,原理剖析

image

  1 package wangyue;
  2 
  3 /**
  4  * 模拟咖啡
  5  * 1、抽象组件:需要装饰的抽象对象(接口或抽象父类)
  6  * 2、具体组件:需要装饰的对象
  7  * 3、抽象装饰类:包含了对抽象组件的引用,以及装饰者共有的方法
  8  * 4、具体装饰类:被装饰的对象
  9  */
 10 public class DecorateTest02 {
 11 
 12     public static void main(String[] args) {
 13         Drink coffee = new Coffee();
 14         Drink sugar = new Sugar(coffee);
 15         System.out.println(sugar.info() + "-->" + sugar.cost());
 16         Drink milk = new Milk(coffee);
 17         System.out.println(milk.info() + "-->" + milk.cost());
 18     }
 19 }
 20 //抽象组件
 21 interface Drink {
 22     double cost();//费用
 23     String info();//说明
 24 }
 25 
 26 //具体组件
 27 class Coffee implements Drink {
 28     private String name = "原味咖啡";
 29 
 30     @Override
 31     public double cost() {
 32         return 10;
 33     }
 34 
 35     @Override
 36     public String info() {
 37         return name;
 38     }
 39 }
 40 
 41 //抽象装饰类
 42 abstract class Decorate implements Drink {
 43 
 44     //对抽象组件的引用
 45     private Drink drink;
 46 
 47     public Decorate(Drink drink) {
 48         this.drink = drink;
 49     }
 50 
 51     @Override
 52     public double cost() {
 53         return this.drink.cost();
 54     }
 55 
 56     @Override
 57     public String info() {
 58         return this.drink.info();
 59     }
 60 }
 61 
 62 //具体的装饰类
 63 class Milk extends Decorate {
 64 
 65     public Milk(Drink drink) {
 66         super(drink);
 67     }
 68     @Override
 69     public double cost() {
 70         return super.cost() * 4;
 71     }
 72 
 73     @Override
 74     public String info() {
 75         return super.info() + "牛奶";
 76     }
 77 }
 78 //具体的装饰类
 79 class Sugar extends Decorate {
 80 
 81     public Sugar(Drink drink) {
 82         super(drink);
 83     }
 84     @Override
 85     public double cost() {
 86         return super.cost() * 2;
 87     }
 88 
 89     @Override
 90     public String info() {
 91         return super.info() + "加入优质方糖";
 92     }
 93 }
 94 
 95 

Guess you like

Origin www.cnblogs.com/Mr-WangYue/p/11628046.html