java IO复习笔记(二)
1、FileInputStream与FileOutputStream(字节输入流与字节输出流)
字节流主要操作byte类型数据,以byte数组为准,主要操作类有InputStream、OutputSteam,由于IputStream和OutputStream都是抽象类,所要要用这两个类的话,则首先要通过子类实例化对象。图片、音频、视频等文件都能通过字节流来处理。
*使用FileInputStream读取文件内容
*步骤:1、new FileInputStream创建一个新对象
2、通过read方法把内容读进一个byte数组中
3、打印数组
1 import java.io.*; 2 class FileStream 3 { 4 public static void readFile()throws IOException 5 { 6 FileInputStream fis = new FileInputStream("fos.txt"); 7 8 byte[] buf = new byte[1024]; 9 int len = 0; 10 while((len=fis.read(buf))!=-1) 11 { 12 System.out.println(new String(buf,0,len)); 13 } 14 15 fis.close(); 16 17 } 18 public static void main(String[] args) throws IOException 19 { 20 readFile(); 21 } 22 }
*使用FileOutputStream写入文件内容
*步骤:1、new FileOutputStream创建一个新对象
2、通过write()方法写入字符串,字符串要用getBytes()方法转为byte类型
1 import java.io.*; 2 class FileStream 3 { 4 public static void writeFile()throws IOException 5 { 6 FileOutputStream fos = new FileOutputStream("fos.txt"); 7 8 9 fos.write("abcde".getBytes()); 10 11 fos.close(); 12 13 14 } 15 public static void main(String[] args) throws IOException 16 { 17 writeFile(); 18 } 19 }
2、InputStreamReader与OutputStreamWriter(转换流)
OutputStreamWriter是Writer的子类,将输出的字符流变为字节流。InputStreamReader是Reader的子类,将输入的字节流变为字符流。
*将字节流转成字符流来使用字符流缓冲区
*步骤:1、使用InputStreamReader创建一个对象,传入BufferedReader
2、while循环读取缓冲区内容
3、创建 一个OutputStreamWriter对象,传入BufferedWriter,打印内容
1 import java.io.*; 2 3 class TransStreamDemo 4 { 5 public static void main(String[] args) throws IOException 6 { 7 //键盘的最常见写法。 8 BufferedReader bufr = 9 new BufferedReader(new InputStreamReader(System.in)); 10 11 BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out)); 12 13 String line = null; 14 15 while((line=bufr.readLine())!=null) 16 { 17 if("over".equals(line)) 18 break; 19 bufw.write(line.toUpperCase()); 20 bufw.newLine(); 21 bufw.flush(); 22 } 23 24 bufr.close(); 25 26 } 27 }
3、装饰设计模式
——简介
当想要对已有的对象进行功能增强时,
可以定义类,将已有对象传入,基于已有的功能,并提供加强功能。
那么自定义的该类称为装饰类。
装饰类通常会通过构造方法接收被装饰的对象。
并基于被装饰的对象的功能,提供更强的功能。
步骤:1、Person类原有chifan方法,现在想增强person的功能
2、把Person对象传入新对象SuperPerson,并实现superChifan方法,在方法内调用原有功能吃饭。
1 class Person 2 { 3 public void chifan() 4 { 5 System.out.println("吃饭"); 6 } 7 } 8 9 class SuperPerson 10 { 11 private Person p ; 12 SuperPerson(Person p) 13 { 14 this.p = p; 15 } 16 public void superChifan() 17 { 18 System.out.println("开胃酒"); 19 p.chifan(); 20 System.out.println("甜点"); 21 System.out.println("来一根"); 22 } 23 } 24 25 class PersonDemo 26 { 27 public static void main(String[] args) 28 { 29 Person p = new Person(); 30 31 //p.chifan(); 32 33 SuperPerson sp = new SuperPerson(p); 34 sp.superChifan(); 35 36 } 37 }
——装饰设计模式与继承的对比
装饰模式比继承要灵活。避免了继承体系臃肿。
而且降低了类于类之间的关系。
装饰类因为增强已有对象,具备的功能和已有的是相同的,只不过提供了更强功能。
所以装饰类和被装饰类通常是都属于一个体系中的。
浙公网安备 33010602011771号