zoukankan      html  css  js  c++  java
  • Java分享笔记:FileInputStream流的 read()方法 和 read(byte[] b)方法

     1 /*------------------------
     2 FileInputStream:
     3 ....//输入流,字节流
     4 ....//从硬盘中存在的一个文件中读取内容,读取到程序中
     5 ....//read()方法:从此输入流中读取一个数据字节
     6 ....//read(byte[] b)方法:从此输入流中将最多b.length个字节的数据读入一个字节数组中
     7 --------------------------*/
     8 package pack01;
     9 
    10 import java.io.*;
    11 
    12 public class Demo {
    13     public static void main(String[] args) throws Exception {
    14     
    15         TestMethod1();
    16         TestMethod2();
    17     }
    18     
    19     //测试read()方法
    20     public static void TestMethod1() throws Exception{
    21         
    22         File file1 = new File("d:/TEST/MyFile1.txt"); //创建一个File类的对象
    23         FileInputStream fis = new FileInputStream(file1); //创建一个FileInputStream类对象,用来操作文件对象file1
    24         
    25         //read()方法:读取文件的一个字节,当执行到文件内容末尾时返回-1
    26         int a;
    27         while( (a=fis.read()) != -1 ) {
    28             System.out.print( (char)a ); //将数字转换为对应的字符
    29         }
    30         System.out.println();
    31         
    32         //close()方法:关闭相应的流
    33         fis.close();
    34     }
    35     
    36     //测试read(byte[] b)方法
    37     public static void TestMethod2() throws Exception{
    38         
    39         File file1 = new File("d:/TEST/MyFile1.txt");
    40         FileInputStream fis = new FileInputStream(file1);
    41         
    42         byte[] arr = new byte[5]; //用来存入从read(byte[] b)方法获取的文件内容
    43         int len; //用来存储read(byte[] b)方法的返回值,代表每次读入的字节个数;当因为到达文件末尾而没有字节读入时,返回-1
    44         while( (len=fis.read(arr)) != -1 ) {
    45             for( int i=0; i<len; ++i )
    46                 System.out.print((char)arr[i]);
    47         }
    48         System.out.println();
    49         
    50         fis.close();
    51     }
    52 }

    注:希望与各位读者相互交流,共同学习进步。

  • 相关阅读:
    【Shell】Shell介绍及常用shell脚本
    【Redis】Redis底层数据结构原理--简单动态字符串 链表 字典 跳跃表 整数集合 压缩列表等
    检查Mysql主从状态
    三种方式获取随机字符串或数字
    Intellij 编译时报 未结束的字符串字面值
    IDEA 远程调试
    kafka操作命令
    maven idea设置查找依赖优先从指定的本地仓库获取
    详解布隆过滤器的原理、使用场景和注意事项
    IDEA查找接口实现类及快速实现接口
  • 原文地址:https://www.cnblogs.com/EarthPioneer/p/9359372.html
Copyright © 2011-2022 走看看