1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 6 7 public class Demo4 { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) { 13 getFile(); 14 15 } 16 public static void getFile() { 17 //找到目標文件 18 File file = new File("C:\\cc\\tt.txt"); 19 //創建通道 20 FileInputStream inputStream = null; 21 try { 22 inputStream = new FileInputStream(file); 23 //建立一個緩衝區 24 byte[] b = new byte[1024]; 25 try { 26 int count = inputStream.read(b); 27 System.out.println(new String(b, 0, count)); 28 } catch (IOException e) { 29 System.out.println("硬盤損壞了,請修理"); 30 throw new RuntimeException(e); 31 } 32 } catch (FileNotFoundException e) { 33 System.out.println("文件不存在"); 34 //提示用戶有錯誤要修改 35 //讓後面的代碼中止運行 36 throw new RuntimeException(e); // 建立一個運行時異常 37 } finally { 38 try { 39 inputStream.close(); 40 } catch (IOException e) { 41 System.out.println("關閉失敗"); 42 throw new RuntimeException(e); 43 } 44 } 45 } 46 47 48 }