package com.io.ioDemo;
/**為什麼要手動的關閉IO流?
* 因為程式中打開的io流不屬于記憶體當中的資源,是以垃圾回收機制就無法回收,是以就要顯示關閉io流。
* */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//問題:檔案裡的中文會亂碼
public class FileInputStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;
try {
//1建立檔案位元組輸入流
fis = new FileInputStream(new File("c:\\fis.txt"));
//2建立用于存儲位元組的數組
byte[] bt = new byte[1024];
//3建立int型變量,用來表示讀入的位元組數
int hasread = 0;
StringBuffer sb = new StringBuffer();
//4循環擷取資料
while((hasread = fis.read(bt))!=-1){
//5把位元組數組轉換成字元串輸出
sb.append(new String(bt,0,hasread));
}
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//6關閉輸入流
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}