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