使用流读取文件内容[IO流经典代码]

时间:2019-06-12
本文章向大家介绍使用流读取文件内容[IO流经典代码],主要包括使用流读取文件内容[IO流经典代码]使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.使用IO流读取文件内容,在实际开发过程中,我们通常不知道文件内容,因此需要读取文件内容,使用流读取文件,配合while循环语句使用。

 1 import java.io.FileInputStream;
 2 import java.io.IOException;
 3 
 4 public class Test {
 5     public static void main(String[] args) {
 6         FileInputStream fis = null;
 7         StringBuffer sb = new StringBuffer();
 8         
 9         try {
10             //1.建立通道
11             fis = new FileInputStream("d:/javatest/a.txt");  //c.txt里是一首诗
12             //InputStreamReader isr = new InputStreamReader(fis,"utf-8");
13             byte[] bytes = new byte[1024];
14             //3.循环读取文件
15             int temp = 0; //当temp=-1时,表示文件已经读取到结尾,停止读取
16             while ((temp = fis.read(bytes)) != -1) {
17                 String str = new String(bytes,0,temp);
18                 sb.append(str);
19                 
20             }
21             
22             System.out.println(sb.toString());
23             
24         } catch (Exception e) {
25             // TODO Auto-generated catch block
26             e.printStackTrace();
27         }finally {
28             /*这样写保证了,即使遇到异常*/
29             try {
30                 fis.close();
31             } catch (IOException e) {
32                 // TODO Auto-generated catch block
33                 e.printStackTrace();
34             }
35             
36         }
37 
38     }
39 
40 }

原文地址:https://www.cnblogs.com/abcdjava/p/11010588.html