package cn.itcast_02;import java.io.FileInputStream;import java.io.IOException;/* * 一次讀取一個字節數組:int read(byte[] b) * 返回其實是實際讀取取的字節個數。 */public class FileInputStreamDemo2 { public static void main(String[] args) throws IOException { // 創建字節輸入流對象 // FileInputStream fis = new FileInputStream("fis2.txt"); FileInputStream fis = new FileInputStream("FileOutputStreamDemo.java"); // 讀取數據 // 定義一個字節數組 // 第一次讀取 // byte[] bys = new byte[5]; // int len = fis.read(bys); // System.out.PRintln(len); // System.out.println(new String(bys, 0, len)); // // // 第二次讀取 // len = fis.read(bys); // System.out.println(len); // System.out.println(new String(bys, 0, len)); // // // 第三次讀取 // len = fis.read(bys); // System.out.println(len); // System.out.println(new String(bys, 0, len)); // // // 第四次讀取 // len = fis.read(bys); // System.out.println(len); // System.out.println(new String(bys, 0, len)); // // 代碼重復了,用循環改進 // // 但是我不知道循環條件 // len = fis.read(bys); // System.err.println(len); // len = fis.read(bys); // System.err.println(len); // 如果讀取到的實際數據是-1,就說明沒有數據了 // byte[] bys = new byte[115]; // int len = 0; // while ((len = fis.read(bys)) != -1) { // System.out.print(new String(bys, 0, len)); // // System.out.println(new String(bys));//千萬要帶上len的使用 // } // 最終代碼版 // 數組的長度一般是1024或者1024的整倍數 byte[] bys = new byte[1024]; int len = 0; while ((len = fis.read(bys)) != -1) { System.out.print(new String(bys, 0, len)); } // 釋放資源 fis.close(); }}
新聞熱點
疑難解答