Java基礎之檔案位元組輸入流(FileInputStream)
阿新 • • 發佈:2021-01-20
1.建立檔案輸入流
有兩個構造方法:
1.FileInputStreamfile =newFileInputStream ("hello.txt");
2.File f = new File("hello.txt");
FileInputStreamfile =newFileInputStream (f );
要注意構造的時候要丟擲異常,不過各種編輯器都會有提示的
看個人習慣可以選一個.
2.使用輸入流讀取檔案
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class wenjian_inputstream { public static void main(String[] args) throws Exception { //InputStreamReader char[] a = new char[1024];//設定每次讀取的位元組 int n ;//設定迴圈結束符 try { InputStreamReader isr = new InputStreamReader(new FileInputStream("hello.txt"), "utf-8"); while ((n = isr.read(a)) != -1) {//設定每次讀取的位元組放到char a[]陣列中,直到檔案末尾返回-1 String s = new String(a, 0, n);//n不可以寫成固定數字,不然讀不完整或超出 System.out.println(s); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //FileInputStream byte[] z = new byte[100];//設定每次讀取的位元組,不知道為什麼設定小於100的報錯 try { FileInputStream file = new FileInputStream("hello.txt"); while ((n = file.read(z, 0, 100)) != -1) {//設定每次讀取的位元組從中間0開始放到byte z[]陣列中,直到檔案末尾返回-1 String s = new String(z, 0, n);//n不可以寫成固定數字,不然讀不完整或超出 System.out.print(s); } file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
其中第一個是用InputStreamReader來進行讀取的位元組,可以對檔案進行轉碼變成utf-8,而要注意的是char[] a = new char[1024];char【】裡面的數字設定為1的時候就會一個一個的進行讀取,效果圖如下
而設定為1024就會一次性讀取1024個位元組.
其中第二個是用FileInputStream來進行讀取的位元組,和第一個大同小異.