1 /*------------------------ 2 FileInputStream: 3 ....//輸入流,字節流 4 ....//從硬盤中存在的一個文件中讀取內容,讀取到程序中 5 ....//read()方法:從此輸入流中讀取一個數據字節 6 ....//read(byte[] b)方法:從此輸入流中將最多b.length個字節的數據讀入一個字節數組中 7 --------------------------*/ 8 package pack01; 9 10 import java.io.*; 11 12 public class Demo { 13 public static void main(String[] args) throws Exception { 14 15 TestMethod1(); 16 TestMethod2(); 17 } 18 19 //測試read()方法 20 public static void TestMethod1() throws Exception{ 21 22 File file1 = new File("d:/TEST/MyFile1.txt"); //創建一個File類的對象 23 FileInputStream fis = new FileInputStream(file1); //創建一個FileInputStream類對象,用來操作文件對象file1 24 25 //read()方法:讀取文件的一個字節,當執行到文件內容末尾時返回-1 26 int a; 27 while( (a=fis.read()) != -1 ) { 28 System.out.print( (char)a ); //將數字轉換為對應的字符 29 } 30 System.out.println(); 31 32 //close()方法:關閉相應的流 33 fis.close(); 34 } 35 36 //測試read(byte[] b)方法 37 public static void TestMethod2() throws Exception{ 38 39 File file1 = new File("d:/TEST/MyFile1.txt"); 40 FileInputStream fis = new FileInputStream(file1); 41 42 byte[] arr = new byte[5]; //用來存入從read(byte[] b)方法獲取的文件內容 43 int len; //用來存儲read(byte[] b)方法的返回值,代表每次讀入的字節個數;當因為到達文件末尾而沒有字節讀入時,返回-1 44 while( (len=fis.read(arr)) != -1 ) { 45 for( int i=0; i<len; ++i ) 46 System.out.print((char)arr[i]); 47 } 48 System.out.println(); 49 50 fis.close(); 51 } 52 }
注:希望與各位讀者相互交流,共同學習進步。
