package cn.itcast_02;import java.io.FileInputStream;import java.io.IOException;/* * 字節輸入流操作步驟: * A:創建字節輸入流對象 * B:調用read()方法讀取數據,并把數據顯示到控制臺 * C:釋放資源 * 讀取數據方式: * A:int read():一次讀取一個字節 * B:int read(byte[] b):一次讀取一個字節數組 */public class FileInputStreamDemo { public static void main(String[] args) throws IOException { // FileInputStream(String name) // FileInputStream fis = new FileInputStream("fis.txt"); FileInputStream fis = new FileInputStream("FileOutputStreamDemo.java"); // 調用read()方法讀取數據,并把數據顯示到控制臺 // 第一次讀取 // int by = fis.read(); // System.out.PRintln(by); // System.out.println((char) by); // // // 第二次讀取 // by = fis.read(); // System.out.println(by); // System.out.println((char) by); // // // 第三次讀取 // by = fis.read(); // System.out.println(by); // System.out.println((char) by); // // //而我們發現代碼的重復度很高,所以我們要用循環改進 // //而用循環,取麻煩的事情是如何用循環控制條件呢? // // 第四次讀取 // by = fis.read(); // System.out.println(by); // // // 第五次讀取 // by = fis.read(); // System.out.println(by); // 通過測試我們知道你讀取的數據量-1,就說明已經讀取到了文件的末尾了 // 用循環改進 // int by = fis.read(); // while (by != -1) { // System.out.println((char) by); // by = fis.read(); // } // 取終代碼 int by = 0; // 讀取,賦值,判斷 while ((by = fis.read()) != -1) { System.out.print((char) by); } // 釋放資源 fis.close(); }}
|
新聞熱點
疑難解答