Java FileInputStream介紹

  • 從文件系統中的某個文件中獲得輸入字節
  • 用於讀取諸如圖像數據之類的原始字節流

方法名 描述
public int read() 從輸入流中讀取一個數據字節
public int read(byte[] b) 從輸入流中將最多b.length個字節的數據讀入一個byte數組中
public int read(byte[] b,int off,int len) 從輸入流中將最多len個字節的數據讀入byte數組中
public void close() 關閉此文件輸入流並釋放與此流有關的所有系統資源

如果返回值爲-1,則表示已經達到文件末尾!

Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputDemo1 {

    public static void main(String[] args) {
        // 創建一個FileInputStream對象
        try {
            FileInputStream fis = new FileInputStream("imooc.txt");
            // int n = fis.read();
            // while(n!=-1){
            // System.out.print((char)n);
            // n=fis.read();
            // }
            int n = 0;
            while ((n = fis.read()) != -1) {
                System.out.print((char) n);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputDemo2 {

    public static void main(String[] args) {
        // 創建一個FileInputStream對象
        try {
            FileInputStream fis = new FileInputStream("imooc.txt");
            byte[] b = new byte[100];
            fis.read(b,0,5);
            System.out.println(new String(b));
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章