《研磨设计模式》chap22 装饰模式Decorator(3)I/O流
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap22 装饰模式Decorator(3)I/O流
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.1
public class IOTest {public static void main(String[] args)throws Exception {//流式讀取文件DataInputStream din = null;try{din = new DataInputStream(new BufferedInputStream(new FileInputStream("IOTest.txt")));//然后就可以獲取文件內(nèi)容了byte bs []= new byte[din.available()]; din.read(bs);String content = new String(bs);System.out.println("文件內(nèi)容===="+content);}finally{din.close();} } }1.2 增加加密功能:第一版
//實(shí)現(xiàn)簡(jiǎn)單的加密 public class EncryptOutputStream extends OutputStream{//持有被裝飾的對(duì)象private OutputStream os = null;public EncryptOutputStream(OutputStream os){this.os = os;} public void write(int a) throws IOException {//先統(tǒng)一向后移動(dòng)兩位a = a+2;//97是小寫的a的碼值if(a >= (97+26)){//如果大于,表示已經(jīng)是y或者z了,減去26就回到a或者b了a = a-26;}this.os.write(a);} } public class Client {public static void main(String[] args) throws Exception {//流式輸出文件DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(new EncryptOutputStream(new FileOutputStream("MyEncrypt.txt"))));//然后就可以輸出內(nèi)容了dout.write("abcdxyz".getBytes());dout.close();} }既然對(duì)象可以隨意組合,那么這樣呢:
public class Client {public static void main(String[] args) throws Exception {//流式輸出文件DataOutputStream dout = new DataOutputStream(new EncryptOutputStream(new BufferedOutputStream(new FileOutputStream("MyEncrypt.txt"))));//然后就可以輸出內(nèi)容了dout.write("abcdxyz".getBytes());dout.close();} }會(huì)有問題,文件為空。
1.3 修改版
//實(shí)現(xiàn)簡(jiǎn)單的加密 public class EncryptOutputStream2 extends java.io.FilterOutputStream{public EncryptOutputStream2(OutputStream os){//調(diào)用父類的構(gòu)造方法super(os);} public void write(int a) throws IOException {//先統(tǒng)一向后移動(dòng)兩位a = a+2;//97是小寫的a的碼值if(a >= (97+26)){//如果大于,表示已經(jīng)是y或者z了,減去26就回到a或者b了a = a-26;}//調(diào)用父類的方法super.write(a);} }總結(jié)
以上是生活随笔為你收集整理的《研磨设计模式》chap22 装饰模式Decorator(3)I/O流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《研磨设计模式》chap22 装饰模式D
- 下一篇: 《研磨设计模式》chap22 装饰模式D