• 使用流读取文件内容[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 }
  • 相关阅读:
    为什么要财务自由
    2019小目标
    《小狗钱钱》后感
    从月光入门到迈出投资第一步
    tslint编译问题-内存溢出
    简单数组
    计算矩阵的乘积
    非数组求杨辉三角
    一维数组求杨辉三角
    二维数组求杨辉三角
  • 原文地址:https://www.cnblogs.com/abcdjava/p/11010588.html
Copyright © 2020-2023  润新知