讀取步驟:
1. 創建源對象
2.創建文件字節輸入流對象(FileInputStream),並接在源上
3.進行IO操作(具體的讀取操作)
4.關閉文件(必不可少的一步,如果操作文件,就得開通一個流對象關聯我們得磁盤文件,如果不關閉資源,那麼磁盤的文件一直被程序所引用着,不能刪除,也不能更改.)
//文件字節輸入流
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
//1 創建源對象
File srcFile = new File("file/src.txt");
//2 創建文件字節輸入流對象,並接在源上
InputStream in = new FileInputStream(srcFile);
//3 IO操作(具體的讀取操作)
/*
* 如果讀到最後沒有數據。則返回-1
* int read() 讀取一個字節,並返回讀取的字節
* int read(byte[] b) 讀取多個字節,並存儲到數組b中,從數組b的索引爲0的地方開始存儲,返回讀取了幾個字節
* int read(byte[] b,int off,int len)讀取len個字節,從數組b的索引爲off的地方開始存儲
*/
//int data = in.read();獲取src.txt 文件中第一個字節
byte[] buffer = new byte[5];
int len = -1;
while((len = in.read(buffer)) != -1){
String str = new String(buffer,0,len);
System.out.println(str);
}
//4 關閉文件
in.close();
}
}