zoukankan      html  css  js  c++  java
  • 使用流读取文件内容[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 }
  • 相关阅读:
    设计模式--单例模式(Singleton)
    C# 和.Net 特性
    Fiddler 教程
    史铁生遗作:昼信基督夜信佛
    如何实现早日退休理想
    Linux 常用
    Golang 读书
    Python 读书
    RbMQ 简介
    UML 简介
  • 原文地址:https://www.cnblogs.com/abcdjava/p/11010588.html
Copyright © 2011-2022 走看看