天天看點

Java中IO流緩沖區的裝飾模式的展現

一、java中io流緩沖區

import java.io.*;

public class bufferedtest

{

public static void copy1()

inputstream is = null;

outputstream os = null;

try

is = new fileinputstream("c:\\xy1.jpg");

os = new fileoutputstream("d:\\xy2.jpg");

int len = 0;

byte[] buffer = new byte[1024];

while ((len = is.read(buffer)) != -1)

os.write(buffer, 0, len);

}

catch (ioexception ex)

throw new runtimeexception("檔案操作出錯");

finally

if (null != is)

is.close();

throw new runtimeexception("輸入流關閉出錯");

if (null != os)

os.close();

throw new runtimeexception("輸出流關閉出錯");

public static void copy2()

bufferedinputstream bis = null;

bufferedoutputstream bos = null;

bis = new bufferedinputstream(is);

bos = new bufferedoutputstream(os);

while ((len = bis.read(buffer)) != -1)

bos.write(buffer, 0, len);

if (null != bis)

bis.close();

if (null != bos)

bos.close();

copy1方法是普通的利用位元組流讀寫檔案的例子。jdk提供了流的緩沖區的概念用來提高讀寫效率,在copy2中可以提現。利用了設計模式的裝飾模式的概念。

二、利用裝飾模式自定義讀取行方法

字元流的緩沖區bufferedreader提供了讀取行的方法,可以一次讀取文本檔案的一行。利用裝飾模式自己實作一個讀取行的方法。

public class myreadline

private reader reader;

public myreadline(reader reader)

super();

this.reader = reader;

public string myreadline() throws ioexception

// 字元緩沖區

stringbuilder sbuilder = new stringbuilder();

// 單個字元的ascii碼值

// 未讀到檔案的末尾

while ((len = reader.read()) != -1)

// windows中換行符是\r\n

if (len == '\r') continue;

if (len == '\n')

// 讀取完了一行,傳回該行内容

return sbuilder.tostring();

else

// 将讀到的有效字元存入緩沖區

sbuilder.append((char) len);

// 最後一行可能沒有換行符,若判斷出現換行符再傳回值就讀取不到最後一行。故判斷緩沖區内是否有值,若有值就傳回。

if (sbuilder.length() != 0)

return null;

public void myclose() throws ioexception

reader.close();

public reader getreader()

return reader;

public void setreader(reader reader)

public class myreadlinetest

public static void main(string[] args)

myreadline myreader = null;

stringbuilder sbresult = new stringbuilder();

myreader = new myreadline(new filereader("c:\\aaa.txt"));

string line = null;

while ((line = myreader.myreadline()) != null)

sbresult.append(line);

system.out.println(sbresult.tostring());

catch (ioexception e)

throw new runtimeexception("讀取檔案異常");

if (null != myreader)

myreader.myclose();

throw new runtimeexception("關閉失敗");