1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 6 public class Demo4 { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 11 getFile(); 12 } 13 14 public static void getFile() { 15 16 //1.找到目标文件 17 File file = new File("D:\a.txt"); 18 //2.建立通道 19 FileInputStream inputStream = null; 20 try { 21 inputStream = new FileInputStream(file); 22 byte[] b = new byte[1024]; 23 try { 24 int count = inputStream.read(b); 25 System.out.println(new String(b,0,count)); 26 } catch (IOException e) { 27 28 System.out.println("硬盘损坏了,请修理"); 29 30 throw new RuntimeException(e); 31 } 32 33 34 } catch (FileNotFoundException e) { 35 36 System.out.println("文件不存在"); 37 //提示用户有错误要修改 38 //让后面的代码定制运行 39 //System.exit(0); 不太好,一般是不随意推出虚拟机。 40 throw new RuntimeException(e); //创建一个运行时异常 41 }finally { 42 43 try { 44 inputStream.close(); 45 } catch (IOException e) { 46 System.out.println("关闭失败"); 47 throw new RuntimeException(e); 48 } 49 } 55 } 57 }