一、InputStream 概述
InputStream 是 Java 中輸入流的抽象類,它是字節輸入流的父類,實現者必須定義 read() 方法,以便從輸入流中讀取字節。InputStream 在讀取數據時,按照字節為單位從輸入流中讀取數據,並返回讀取的數據。
InputStream 類的常用方法如下:
public abstract int read() throws IOException; public int read(byte[] b) throws IOException; public int read(byte[] b, int off, int len) throws IOException; public long skip(long n) throws IOException; public int available() throws IOException; public void close() throws IOException; public synchronized void mark(int readlimit); public synchronized void reset() throws IOException; public boolean markSupported();
其中,常用的方法有:
- read():讀取輸入流中的字節,返回讀取的字節碼;
- read(byte[] b):將輸入流中的字節讀入到字節數組中 b,返回讀入的字節數量;
- read(byte[] b, int off, int len):將輸入流中的字節的 len 個讀入到字節數組 b 中,從字節數組的 off 位置開始存儲,返回讀入的字節數量;
- skip(long n):從輸入流中跳過 n 個字節的數據;
- available():返回輸入流中還未讀入的字節數;
- close():關閉輸入流的實例。
二、InputStream 的子類
1. FileInputStream
FileInputStream 是 InputStream 子類之一,它從文件中讀取數據。FileInputStream 可以接受文件路徑或 File 對象,讀取指定文件。
示例代碼:
File file = new File("test.txt"); InputStream inputStream = new FileInputStream(file); int data; while ((data = inputStream.read()) != -1) { System.out.print((char)data); } inputStream.close();
2. ByteArrayInputStream
ByteArrayInputStream 是 InputStream 的另一個子類,它可以從字節數組中讀取數據。使用 ByteArrayInputStream 時,需要將要讀取的字節數組傳遞給 ByteArrayInputStream 的構造函數。
示例代碼:
byte[] byteArray = "Hello, world!".getBytes(); InputStream inputStream = new ByteArrayInputStream(byteArray); int data; while ((data = inputStream.read()) != -1) { System.out.print((char)data); } inputStream.close();
三、InputStream 的使用注意事項
1. InputStream 的關閉
在讀取完畢數據後,需要關閉 InputStream,否則資源無法釋放。使用 try-with-resources 語句可以在讀取完畢後自動關閉 InputStream。
示例代碼:
File file = new File("test.txt"); try (InputStream inputStream = new FileInputStream(file)) { int data; while ((data = inputStream.read()) != -1) { System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); }
2. 字符集(Charset)的指定
在將 InputStream 中的字節轉換為字符時,需要指定字符集以避免亂碼問題。Java 中常見的字符集有 UTF-8、GBK、ISO8859-1 等。
示例代碼:
File file = new File("test.txt"); try (InputStream inputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { int data; while ((data = inputStreamReader.read()) != -1) { System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); }
3. 緩衝區(Buffer)的使用
在讀取大文件時,可以通過使用緩衝區來提高讀取速度。
示例代碼:
File file = new File("large_file.txt"); try (InputStream inputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { int data; while ((data = bufferedInputStream.read()) != -1) { System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); }
四、小結
InputStream 是 Java 中輸入流的抽象類,通過不同的子類對不同來源(如文件、字節數組)的輸入流進行操作。在使用 InputStream 時,需要注意數據的關閉、字符集的指定以及緩衝區的使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/199544.html