使用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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM