FileInputStream中read()方法在參數不同時的返回值說明


read()空參數,作用是“從此輸入流中讀取一個數據字節。”,返回值為讀取到的字節並強轉為int形式

public class P01Stream {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File f = new File("D:\\lol2.txt");//“ABC”
        FileInputStream fis = new FileInputStream(f);
        int len = 0;
        
        while((len = fis.read()) != -1)
            System.out.println(len);        
    }
}
//輸出結果:
//65
//66
//67

read(byte[] b)時,作用是“從此輸入流中將最多b.length 個字節的數據讀入一個 byte 數組中。”返回值是讀取到的字節個數。

public class P01Stream {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File f = new File("D:\\lol2.txt");//"ABC"
        FileInputStream fis = new FileInputStream(f);
        int len = 0;
        byte[] bytes = new byte[(int) f.length()];
        
        while((len = fis.read(bytes)) != -1)
            System.out.println(len);        
    }
}
//輸出結果
//3

該byte數組作為緩沖數組,存儲了讀取到的字節

public class P01Stream {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File f = new File("D:\\lol2.txt");//"ABC"
        FileInputStream fis = new FileInputStream(f);
        int len = 0;
        byte[] bytes = new byte[(int) f.length()];
        
        while((len = fis.read(bytes)) != -1) {
            for (byte b : bytes) {
                System.out.println(b);
            }
            
        }
                    
    }
}
//輸出結果
//65
//66
//67


免責聲明!

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



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