W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
在Java I/O中,流意味著數(shù)據(jù)流。流中的數(shù)據(jù)可以是字節(jié),字符,對(duì)象等。
要從文件讀取,我們需要?jiǎng)?chuàng)建一個(gè)FileInputStream類(lèi)的對(duì)象,它將表示輸入流。
String srcFile = "test.txt"; FileInputStream fin = new FileInputStream(srcFile);
如果文件不存在,F(xiàn)ileInputStream類(lèi)的構(gòu)造函數(shù)將拋出FileNotFoundException異常。要處理這個(gè)異常,我們需要將你的代碼放在try-catch塊中,如下所示:
try { FileInputStream fin = new FileInputStream(srcFile); }catch (FileNotFoundException e){ // The error handling code goes here }
FileInputStream類(lèi)有一個(gè)重載的read()方法從文件中讀取數(shù)據(jù)。我們可以一次讀取一個(gè)字節(jié)或多個(gè)字節(jié)。
read()方法的返回類(lèi)型是int,雖然它返回一個(gè)字節(jié)值。如果到達(dá)文件的結(jié)尾,則返回-1。
我們需要將返回的int值轉(zhuǎn)換為一個(gè)字節(jié),以便從文件中讀取字節(jié)。通常,我們?cè)谘h(huán)中一次讀取一個(gè)字節(jié)。
最后,我們需要使用close()方法關(guān)閉輸入流。
// Close the input stream fin.close();
close()方法可能拋出一個(gè)IOException,因此,我們需要在try-catch塊中包含這個(gè)調(diào)用。
try { fin.close(); }catch (IOException e) { e.printStackTrace(); }
通常,我們?cè)趖ry塊中構(gòu)造一個(gè)輸入流,并在finally塊中關(guān)閉它,以確保它在我們完成后總是關(guān)閉。
所有輸入/輸出流都可自動(dòng)關(guān)閉。我們可以使用try-with-resources來(lái)創(chuàng)建它們的實(shí)例,所以無(wú)論是否拋出異常,它們都會(huì)自動(dòng)關(guān)閉,避免需要顯式地調(diào)用它們的close()方法。
以下代碼顯示使用try-with-resources創(chuàng)建文件輸入流:
String srcFile = "test.txt"; try (FileInputStream fin = new FileInputStream(srcFile)) { // Use fin to read data from the file here } catch (FileNotFoundException e) { // Handle the exception here }
以下代碼顯示了如何從文件輸入流一次讀取一個(gè)字節(jié)。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Main { public static void main(String[] args) { String dataSourceFile = "asdf.txt"; try (FileInputStream fin = new FileInputStream(dataSourceFile)) { byte byteData; while ((byteData = (byte) fin.read()) != -1) { System.out.print((char) byteData); } } catch (FileNotFoundException e) { ; } catch (IOException e) { e.printStackTrace(); } } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: