使用流读取文件内容[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值