使用FileInputStream 读文本文件

 1     
 2     @Test
 3     public void test02(){
 4         
 5         //1.创建File类
 6         File file = new File("KH87");
 7         //2.创建合适的流
 8         FileInputStream fis = null;
 9         try {
10             fis = new FileInputStream(file);
11             //创建byte数组
12             byte[] buffer = new byte[50];
13             //优化前,代码量多
14             //调用FileInputStream  中的read()方法
15             //3.读取操作
16 //            int len = fis.read(b);
17 //            while(len!=-1){
18 //                for(int i = 0; i < len; i++){
19 //                    System.out.print((char)b[i]);
20 //                }
21 //                len = fis.read(b);
22 //            }
23             
24             //优化后,代码简洁,减少冗余
25             //3.读取操作
26             int len;
27             while((len = fis.read(buffer)) != -1){
28                 String str = new String(buffer, 0, len);
29                 System.out.print(str);
30             }
31         } catch (Exception e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         }finally{//肯定会执行的内容
35             try {
36                 //4.关闭流(一定要关闭)
37                 fis.close();
38             } catch (IOException e) {
39                 // TODO Auto-generated catch block
40                 e.printStackTrace();
41             }
42         }
43         
44     }
45     
46     @Test
47     public void test01(){
48         
49         //1.创建file对象
50         File file = new File("KH87");
51         
52         //2.创建合适的流
53         FileInputStream fis = null;
54         try {
55             fis = new FileInputStream(file);
56         //3.读取操作
57         //调用FileInputStream  中的read()方法,一个字节一个字节的读取
58         //直到最后一个内容,返回-1
59             int len = fis.read();
60             while(len != -1){
61                 System.out.print((char)len);
62                 len = fis.read();
63             }
64         } catch (Exception e) {
65             // TODO Auto-generated catch block
66             e.printStackTrace();
67         }finally{//肯定会执行的操作,用finally
68             try {
69                 //4.关闭流(一定要关闭)
70                 fis.close();
71             } catch (IOException e) {
72                 // TODO Auto-generated catch block
73                 e.printStackTrace();
74             }
75         }
76         
77     }

猜你喜欢

转载自www.cnblogs.com/zl225/p/12902097.html