實現文件複製
public static void copyFile(String src, String dist) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dist);
byte[] buffer = new byte[20 * 1024];
int cnt;
// read() 最多讀取 buffer.length 個字節
// 返回的是實際讀取的個數
// 返回 -1 的時候表示讀到 eof,即文件尾
while ((cnt = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, cnt);
}
in.close();
out.close();
}
裝飾者模式
Java I/O 使用了裝飾者模式來實現。
裝飾模式:動態地給一個對象增加一些額外的職責。就擴展功能而言,裝飾模式提供了一種比使用子類更加靈活的替代方案。
裝飾模式的結構:
以 InputStream 爲例,
- InputStream 是抽象組件;
- FileInputStream 是 InputStream 的子類,屬於具體組件,提供了字節流的輸入操作;
- FilterInputStream 屬於抽象裝飾者,裝飾者用於裝飾組件,爲組件提供額外的功能。例如 BufferedInputStream 爲 FileInputStream 提供緩存的功能。
實例化一個具有緩存功能的字節流對象時,只需要在 FileInputStream 對象上再套一層 BufferedInputStream 對象即可。
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
DataInputStream 裝飾者提供了對更多數據類型進行輸入的操作,比如 int、double 等基本類型。