緩沖流
1.緩沖流涉及到的類
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
2.作用
- 提升流的讀取、寫入的速度。
- 原因:内部提供了一個緩沖區,預設情況下是8192,即8kb。
3.使用BufferedInputStream和BufferedOutputStream
處理非文本檔案
//實作檔案複制的方法
public void copyFileWithBuffered(String srcPath,String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.
File srcfile = new File(srcPath);
File destfile = new File(destPath);
//2.
//2.1造節點流
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
//2.2造緩沖流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
// bos.flush();//重新整理緩沖區
}
System.out.println("複制成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.要求:先關閉外層的流,再關閉内層的流
if (bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//說明:關閉外層流的同時,内層流也會自動的進行關閉,關于内層流的關閉,我們可以省略
// fos.close();
// fis.close();
}
對上述方法進行測試:
@Test
public void testCopyBuffererd(){
long start = System.currentTimeMillis();
String srcPath = "1.jpg";
String destPath = "6.jpg";
copyFileWithBuffered(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("複制所需要的毫秒數為:"+ (end - start));
}
4.使用BufferedReader和BufferedWriter:處理文本檔案
//使用BufferedReader和BufferedWriter實作文本檔案的複制
@Test
public void test6(){
BufferedReader br = null;
BufferedWriter bw = null;
try {
//使用匿名方式,建立檔案和相應的流
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
//讀寫操作
//方式一:使用char[]數組
// char[] cbuf = new char[1024];
// int len;
// while ((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// bw.flush();//重新整理操作
// }
//方式二:使用String
String data;
while ((data = br.readLine()) != null){
bw.write(data);
bw.newLine();//提供換行的操作
}
System.out.println("複制成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
//關閉資源
try {
if (bw != null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
願路途漫長,以後莫失莫忘。 願你不驕不躁,安穩順心。
歸檔:我的知識棧:目錄(更新中...)
作者:菜鳥-傳奇