1. 程式人生 > >java緩衝流,資料流和物件流

java緩衝流,資料流和物件流

一:緩衝流
1:定義:在記憶體與硬碟之間建立一個大小合適的緩衝區,當記憶體和硬碟進行資料訪問時,能提高訪問硬碟的次數,提高效率。
2:分類:緩衝分為位元組緩衝流(BufferedInputStream和BufferedOutputStream)和字元緩衝流(BufferedReader和BufferedWrite)。
3:緩衝流對位元組檔案拷貝的應用(程式碼示例):
  public class CopyFile {
public static void main(String[] args) throws IOException {
CopyFile c = new CopyFile();
c.copy();
}


public void copy() throws IOException {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("C:\\Users\\huangxiong\\Desktop\\test.txt"));// 對輸入流進行包裝
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Users\\huangxiong\\Desktop\\test1.txt"));// 對輸出流進行包裝
int len;
while ((len = bis.read()) != -1) {
bos.write(len);
}
bis.close();
bos.close();
}
}
4:緩衝流屬於包裝流,只能對已有的流進行包裝,使原來的流更加強大,執行效率更高,不能關聯檔案。


二:資料流(DataInputStream,DataOutputStream)
1:定義:資料流是對8大基本資料型別的資料進行記憶體與硬碟之間互相訪問的流,屬於包裝流,包裝後使原來的流傳輸資料更加方便
2:分類:資料流只有位元組流,沒有字元流。
3:資料流對檔案的拷貝(程式碼示例)
 
public void copy1() throws IOException{
int a = 201400;
long b = 1000000000;
boolean c = true;
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream
(new FileOutputStream("C:\\Users\\huangxiong\\Desktop\\test.txt")));//用緩衝流和資料流分別對FileOuyputStream進行包裝
   dos.writeInt(a);
dos.writeLong(b);
dos.writeBoolean(c);
dos.close();              //流一結束,就關閉流
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream("C:\\Users\\huangxiong\\Desktop\\test.txt")));
int a1 = dis.readInt();
long b1 = dis.readLong();
boolean c1 = dis.readBoolean();
System.out.println(a1);
System.out.println(b1);
System.out.println(c1);
dis.close();
}

三:物件流(ObjectInputStream,ObjectOutputStream)

1:定義:物件流傳輸的是一個物件,在我們需要儲存一個物件的很多屬性的時候,用物件流可以簡化程式碼,更加方便2:分類:輸入物件流和輸出物件流

2:物件流也屬於包裝流,包裝後使原來的流具有對物件進行讀寫的功能

3:物件流實現物件的拷貝(程式碼示例)
try {
//把物件寫入檔案
ArrayList<Student> list = new ArrayList<Student>();
Student stu = new Student("張三",30);
list.add(stu);
//物件流操作,直接寫入或者讀入物件
FileOutputStream fos = new FileOutputStream("test_4.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//可以直接寫出物件
oos.writeObject(list);
oos.flush();
oos.close();
//從檔案中讀取物件
FileInputStream fis = new FileInputStream("test_4.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
@SuppressWarnings("unchecked")
ArrayList<Student> stuList = (ArrayList<Student>)ois.readObject();
ois.close();
for (int i = 0; i < stuList.size(); i++) {
Student stu1 = stuList.get(i);
System.out.println(stu1.name+"   "+stu1.age);
}
       } catch (Exception e) {
e.printStackTrace();
}
}

             }

Student類:


package com.huaxin.io;
import java.io.Serializable;


public class Student implements Serializable{
public String name;
public int age;

public Student(String name,int age){
this.name = name;
this.age = age;
}
}

注意事項:物件流在讀寫物件時候,必須對物件進行序列化,也就是該物件必須 implements Serializable,這是為了將物件寫成特殊序列的位元組碼檔案,讀檔案的時候,可以還原這個物件。