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 }

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

  • 相关阅读:
    FreeRTOS 移植到WIN10
    Keil debug command SAVE 命令保存文件的解析
    VS2017 编译 Visual Leak Detector + VLD 使用示例
    LaTeX 中插入GIF图片
    VS2017 + Qt5 + OpenCV400 环境配置
    记一次C++编程引用obj文件作为静态库文件
    Qt 多语言支持
    vscode 解决符号无法识别的问题
    带FIFO的UART数据接收
    MySQL Connector/Python 接口 (三)
  • 原文地址:https://www.cnblogs.com/EarthPioneer/p/9359372.html
Copyright © 2011-2022 走看看