在Java中,文件輸入流(FileInputStream)是一種用於讀取文件中的字節一個字節流類。下麵的例子將使用文件輸入流讀取一個名為 “c:/robots.txt” 文件並顯示其內容在控製台中。
//This is content of file : c:/robots.txt User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ Disallow: /wp-includes-test/
請參閱下麵的完整的例子。
package com.yiibai.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { File file = new File("C:/robots.txt"); FileInputStream fis = null; try { fis = new FileInputStream(file); System.out.println("Total file size to read (in bytes) : " + fis.available()); int content; while ((content = fis.read()) != -1) { // convert to char and display it System.out.print((char) content); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
下麵的結果將顯示在控製台上。
Total file size to read (in bytes) : 90 User-agent: * Disallow: /wp-admin/ Disallow: /wp-includes/ Disallow: /wp-includes-test/
JDK 7 實例
更新 JDK7 實例,使用新的“嘗試資源接近”方法來輕鬆處理文件。
package com.yiibai.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { File file = new File("C:/robots.txt"); try (FileInputStream fis = new FileInputStream(file)) { System.out.println("Total file size to read (in bytes) : "+ fis.available()); int content; while ((content = fis.read()) != -1) { // convert to char and display it System.out.print((char) content); } } catch (IOException e) { e.printStackTrace(); } } }