字節流讀數據(一次讀取一個字節數組)


通過之前一次讀取一個字節數據的示例中,發現當讀取到流的末尾是會返回-1,讀取字節數組時同樣也是返回-1時作為終止循環的條件

public class FileInputDemo01 {
    public static void main(String[] args) throws IOException {
        //創建字節輸入流對象
        FileInputStream fis = new FileInputStream("myFile\\fos.txt");

        //調用字節輸入流對象的讀數據方法
        //int read(byte[] b):從該輸入流讀取最多 b.length個字節的數據為字節數組。
        //首先要有一個字節數組作為存儲數據的容器
        byte[] bys = new byte[1024];
        int len; //len代表讀取到的數據的長度
        /*
            len變量的含義:假如字節數組中有5個字節數據時,該值等於5,有100個字節數據時,該值就等於100
         */
        while ((len = fis.read(bys)) != -1) {
            //String(byte[] bytes, int offset, int length)
            System.out.println(new String(bys,0,len));
        }

        //釋放資源
        fis.close();
    }
}

fos.txt中內容為:

 

運行結果:

 

修改fos.txt內容:

 

 運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM