一、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
{
try
{
if (null != is)
{
is.close();
}
}
catch (IOException ex)
{
throw new RuntimeException("輸入流關閉出錯");
}
try
{
if (null != os)
{
os.close();
}
}
catch (IOException ex)
{
throw new RuntimeException("輸出流關閉出錯");
}
}
}
public static void copy2()
{
InputStream is = null;
BufferedInputStream bis = null;
OutputStream os = null;
BufferedOutputStream bos = null;
try
{
is = new FileInputStream("c:\\xy1.jpg");
bis = new BufferedInputStream(is);
os = new FileOutputStream("d:\\xy2.jpg");
bos = new BufferedOutputStream(os);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) != -1)
{
bos.write(buffer, 0, len);
}
}
catch (IOException ex)
{
throw new RuntimeException("文件操作出錯");
}
finally
{
try
{
if (null != bis)
{
bis.close();
}
}
catch (IOException ex)
{
throw new RuntimeException("輸入流關閉出錯");
}
try
{
if (null != bos)
{
bos.close();
}
}
catch (IOException ex)
{
throw new RuntimeException("輸出流關閉出錯");
}
}
}
}
copy1方法是普通的利用字節流讀寫文件的例子。JDK提供了流的緩沖區的概念用來提高讀寫效率,在copy2中可以提現。利用了設計模式的裝飾模式的概念。
Java 8 徹底改變數據庫訪問 http://www.linuxidc.com/Linux/2014-03/98947.htm
二、利用裝飾模式自定義讀取行方法
字符流的緩沖區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碼值
int len = 0;
// 未讀到文件的末尾
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 sbuilder.toString();
}
return null;
}
public void myclose() throws IOException
{
reader.close();
}
public Reader getReader()
{
return reader;
}
public void setReader(Reader reader)
{
this.reader = reader;
}
}
public class MyReadLineTest
{
public static void main(String[] args)
{
MyReadLine myReader = null;
try
{
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("讀取文件異常");
}
finally
{
try
{
if (null != myReader)
{
myReader.myclose();
}
}
catch (IOException e)
{
throw new RuntimeException("關閉失敗");
}
}
}
}