Java類庫裡有四個表示流的抽象父類:InputStream、OutputStream、Reader、Writer。
其中 InputStream 和 OutputStream 是對字節進行操作的輸入流和輸出流;Reader 和 Writer 是對字符操作的輸入輸出流。
它們是抽象類,在用它們的時候必須要對其進行實例化,因此類庫也提供了具有不同功能的它們的子類,比如,以文件形式輸入輸出的FileInputStream、FileOutputStream和FileReader、FileWriter等。
--------------------------------------------------------------
一、字節流
1. InputStream、OutputStream 只能進行字節的傳輸數據
InputStream抽象了應用程序讀取數據的方式
OutputStream抽象了應用程序寫出數據的方式
2. EOF = End,讀到 -1 就讀到結尾。
3. 輸入流的基本方法(以下的 in 代表輸入流的對象)
int b = in.read();
從流讀取一個字節無符號填充到int的低8位。(一個int變量是4個字節,1字節=8位,read()方法只能讀取一個字節並返回int,所以該字節填充到int的低八位。)若讀到結尾,返回 -1。
in.read(byte[] buf);
從流讀取數據直接填充到字節數組buf,讀取字節的個數取決於數組的長度。
in.read(byte[] buf, int start, int size);
從流讀取數據到字節數組buf,從buf的start位置開始,存放size長度的數據。
4. 輸出流的基本方法(以下的 out 代表輸出流的對象)
out.write(int b);
寫出一個byte到流,寫出的是b的低8位。
out.write(byte[] buf);
將一個字節數組寫出到流。
out.write(byte[] buf, int start, int size);
從buf的start位置開始,寫size長度的數據到流。
5. FileInputStream 是InputStream的子類,具體實現了在文件上讀取數據:

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class TestDemo {
public static void main(String[] args) throws Exception {
//我們在D盤下創建了一個demo.txt,內容為“你好hello”。
File file = new File("D:\\demo.txt");
if(!file.exists()) file.createNewFile();
InputStream in = new FileInputStream(file);
int temp;
while((temp = in.read()) != -1) {
System.out.print(Integer.toHexString(temp & 0xff) + " ");
}
in.close();
System.out.println();
InputStream in2 = new FileInputStream(file);
byte[] buf = new byte[1024];
in2.read(buf);
String s = new String(buf,"GBK");
System.out.println(s);
in2.close();
}
}
TestDemo
Output: c4 e3 ba c3 68 65 6c 6c 6f
你好hello