1.IO體系:
- 抽象基類——節點流(檔案流)——緩衝流(處理流的一種)
- InputStream ——FileInputStream——BufferedInputStream
- OutputStream——FileOutputSteam——BufferedOutputStream(flush())
- Reader——FileReader——BufferedReder(readLine())
- Writer——FileWriter——BufferedWriter(flush())
2.分類
處理流之一:
- 緩衝流:BufferedInputStream和BufferedOutputStream(位元組流)
用於處用於處理視訊檔案、音訊檔案、圖片、.doc等非文字檔案,作用:加速檔案傳輸
緩衝流:BufferedReader和BufferedWriter(字元流)
- 主要用於處理純文字檔案(.txt)。
3.程式碼例項
位元組緩衝流
public class BufferedInputOutputStream {
//計算使用緩衝流BufferedInputStream和BufferedOutputStream傳輸非文字檔案的時間
@Test
public void spendTime(){
long start = System.currentTimeMillis();
String src = "file/1.mp4";
String dest = "file/2.mp4";
testBufferedInputOutputStream(src,dest);
long end = System.currentTimeMillis();
System.out.println("花費時間為:"+(end - start));//時間為504毫秒
}
//使用緩衝流把非文字檔案複製一份
//@Test
public void testBufferedInputOutputStream(String src,String dest){
//3.建立緩衝流物件
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.File類物件
File file1 = new File(src);
File file2 = new File(dest);
//2.建立節點流物件
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int len;
//4.開始讀取檔案,寫入檔案
while((len = bis.read(b)) != -1){
bos.write(b,0,len);
//flush()是強行將緩衝區中的內容輸出,否則直到緩衝區滿後才會一次性的將內容輸出
bos.flush();//重新整理
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(bos != null){
//5.關閉流
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
字元緩衝流
public class BufferedReaderWriter {
//把檔案檔案複製到另一個文字檔案
@Test
public void testBufferedReaderWriter(){
//3.定義兩個緩衝流
BufferedReader br = null;
BufferedWriter bw = null;
try {
//1.定義兩個檔案物件
File file = new File("file/hello.txt");
File file1 = new File("file/hello5.txt");
//2.定義兩個節點流
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(file1);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//4.開始讀取檔案——方法一
/*char[] c = new char[1024];
int len;
while((len = br.read(c)) != -1){
bw.write(c, 0, len);
}*/
//開始讀取檔案——方法二
String str;
while((str = br.readLine()) != null){
bw.write(str+"\n");//或者bw.newLine();
bw.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//5.關閉
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bw != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}