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