BufferedInputStream使用詳解


下面的例子演示如何使用BufferedInputStream類讀取文本文件內容。

首先需要聲明一個byte數組作為buffer,然后循環將文本內容循環讀入到buffer中,並將buffer轉換為字符串,打印到控制台。

/**
*
* @author outofmemory.cn
*/
public class Main {

    /**
     * 從文件中讀取文本
*/
public void readFromFile(String filename) {

        BufferedInputStream bufferedInput = null;
        byte[] buffer = new byte[1024];

        try {

            //創建BufferedInputStream 對象
bufferedInput = new BufferedInputStream(new FileInputStream(filename));

            int bytesRead = 0;

            //從文件中按字節讀取內容,到文件尾部時read方法將返回-1
            while ((bytesRead = bufferedInput.read(buffer)) != -1) {

                //將讀取的字節轉為字符串對象
String chunk = new String(buffer, 0, bytesRead);
                System.out.print(chunk);
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //關閉 BufferedInputStream
            try {
                if (bufferedInput != null)
                    bufferedInput.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * @param args 命令行參數
*/
public static void main(String[] args) {
        new Main().readFromFile("myFile.txt");
    }
}

使用方法

  BufferedInputStream繼承於FilterInputStream,提供緩沖輸入流功能。緩沖輸入流相對於普通輸入流的優勢是,它提供了一個緩沖數組,每次調用read方法的時候,它首先嘗試從緩沖區里讀取數據,若讀取失敗(緩沖區無可讀數據),則選擇從物理數據源(譬如文件)讀取新數據(這里會嘗試盡可能讀取多的字節)放入到緩沖區中,最后再將緩沖區中的內容部分或全部返回給用戶.由於從緩沖區里讀取數據遠比直接從物理數據源(譬如文件)讀取速度快。

方法介紹

  BufferedInputStream提供的API如下:

//構造方法 BufferedInputStream(InputStream in) BufferedInputStream(InputStream in, int size) //下一字節是否可讀 synchronized int available() //關閉 void close() //標記, readlimit為mark后最多可讀取的字節數 synchronized void mark(int readlimit) //是否支持mark, true boolean markSupported() //讀取一個字節 synchronized int read() //讀取多個字節到b synchronized int read(byte[] b, int off, int len) //重置會mark位置 synchronized void reset() //跳過n個字節 synchronized long skip(long n)

 

使用示例

public void testBufferedInput() { try { /** * 建立輸入流 BufferedInputStream, 緩沖區大小為8 * buffer.txt內容為 * abcdefghij */ InputStream in = new BufferedInputStream(new FileInputStream(new File("buff.txt")), 8); /*從字節流中讀取5個字節*/ byte [] tmp = new byte[5]; in.read(tmp, 0, 5); System.out.println("字節流的前5個字節為: " + new String(tmp)); /*標記測試*/ in.mark(6); /*讀取5個字節*/ in.read(tmp, 0, 5); System.out.println("字節流中第6到10個字節為: " + new String(tmp)); /*reset*/ in.reset(); System.out.printf("reset后讀取的第一個字節為: %c" , in.read()); } catch (Exception e) { e.printStackTrace(); } }

  運行結果如下:

字節流的前5個字節為: abcde 字節流中第6到10個字節為: fghij reset后讀取的第一個字節為: f



使用BufferedInputStream和BufferedOuputStream讀寫圖片

 

使用方式和FileInputStrem和FileOutputStream基本一致:

 

[java]  view plain  copy
 
  1. package org.example.io;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8.   
  9. public class TestBufferedString {  
  10.   
  11.     public static void main(String[] args) throws Exception {  
  12.         // 指定要讀取文件的緩沖輸入字節流  
  13.         BufferedInputStream in = new BufferedInputStream(new FileInputStream("F:\\test.jpg"));  
  14.         File file = new File("E:\\test.jpg");  
  15.         if (file != null) {  
  16.             file.createNewFile();  
  17.         }  
  18.         // 指定要寫入文件的緩沖輸出字節流  
  19.         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));  
  20.         byte[] bb = new byte[1024];// 用來存儲每次讀取到的字節數組  
  21.         int n;// 每次讀取到的字節數組的長度  
  22.         while ((n = in.read(bb)) != -1) {  
  23.             out.write(bb, 0, n);// 寫入到輸出流  
  24.         }  
  25.         out.close();// 關閉流  
  26.         in.close();  
  27.     }  
  28.   
  29. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM