一、FileInputStream概覽
FileInputStream是Java IO庫中為讀取文件提供的一種輸入流,可以用來讀取文件中的字節數據。FileInputStream會默認以字節的形式讀取文件數據,它包含了多個構造函數以方便開發者進行使用。
下面是一個簡單的文件讀取示例:
File file = new File("test.txt"); FileInputStream fis = new FileInputStream(file); int ch; while((ch = fis.read()) != -1) { System.out.print((char)ch); } fis.close();
這段代碼首先創建了一個File對象,並指定它要讀取的文件名為test.txt,接着創建了一個FileInputStream對象,並將File對象作為參數傳入構造函數中。通過調用FileInputStream的read()方法,可以不斷讀取文件的字節數據並將其打印到控制台上。
二、FileInputStream的常用方法
FileInputStream提供了多個常用方法,下面簡單介紹幾個。
1. read()
FileInputStream的read()方法可以讀取一個字節的數據,並返回一個int類型的字符,如果已經讀取到文件結尾,則返回-1。例如:
FileInputStream fis = new FileInputStream("test.txt"); int ch = fis.read(); System.out.println((char)ch); fis.close();
這段代碼將讀取test.txt文件的第一個字節,將其轉換成字符類型後打印到控制台上。
2. available()
FileInputStream的available()方法可以獲取文件還未讀取的字節數,例如:
FileInputStream fis = new FileInputStream("test.txt"); System.out.println(fis.available()); fis.close();
這段代碼將打印出文件test.txt中還未讀取的字節數。
3. skip()
FileInputStream的skip()方法可以跳過指定的字節數,例如:
FileInputStream fis = new FileInputStream("test.txt"); fis.skip(10); int ch; while((ch = fis.read()) != -1) { System.out.print((char)ch); } fis.close();
這段代碼將跳過test.txt文件的前10個字節,然後讀取剩下的字節數據並打印到控制台上。
三、關閉FileInputStream
當我們完成對文件數據的讀取後,必須關閉FileInputStream以釋放資源。關閉流的操作非常簡單,只需要調用FileInputStream的close()方法即可:
FileInputStream fis = new FileInputStream("test.txt"); // do some operations fis.close();
如果在操作過程中出現了異常,也同樣需要保證FileInputStream被正確關閉。這裡我們可以使用try-catch-finally語句來確保FileInputStream能夠被正常關閉:
FileInputStream fis = null; try { fis = new FileInputStream("test.txt"); // do some operations } catch (IOException e) { e.printStackTrace(); } finally { if(fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
四、總結
FileInputStream是Java IO庫中為讀取文件提供的一種輸入流,它提供了多個方法可以方便開發者進行文件讀取操作。使用時需要注意關閉流以釋放資源。
原創文章,作者:QABY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/149451.html