IO/InputStream

1./**
* 根據read方法返回值的特性,如果獨到文件的末尾返回-1,如果不爲-1就繼續向下讀。
* */
private static void showContent(String path) throws IOException {
// 打開流
FileInputStream fis = new FileInputStream(path);
int len = fis.read();
while (len != -1) {
System.out.print((char)len);
len = fis.read();
}
// 使用完關閉流
fis.close();
}
2./**
* 使用字節數組存儲讀到的數據
* */
private static void showContent2(String path) throws IOException {
// 打開流
FileInputStream fis = new FileInputStream(path);

    // 通過流讀取內容
    byte[] byt = new byte[1024];//緩衝區太小,數據讀取不完
    int len = fis.read(byt);
    for (int i = 0; i < byt.length; i++) {
        System.out.print((char) byt[i]);
    }

    // 使用完關閉流
    fis.close();
}
3./**
 * 把數組的一部分當做流的容器來使用
 * read(byte[] b,int off,int len)
 */
private static void showContent3(String path) throws IOException {
    // 打開流
    FileInputStream fis = new FileInputStream(path);

    // 通過流讀取內容
    byte[] byt = new byte[1024];
    // 從什麼地方開始存讀到的數據
    int start = 5;

    // 希望最多讀多少個(如果是流的末尾,流中沒有足夠數據)
    int maxLen = 6;

    // 實際存放了多少個
    int len = fis.read(byt, start, maxLen);

    for (int i = start; i < start + maxLen; i++) {
        System.out.print((char) byt[i]);
    }

    // 使用完關閉流
    fis.close();
}

4./**
* 使用字節數組當緩衝
* */
private static void showContent5(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
byte[] byt = new byte[1024];
int len = fis.read(byt);
System.out.println(len);
String buffer = new String(byt, 0, len);
System.out.print(buffer,0,len);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章