Java分享笔记:FileInputStream流的 read()方法 和 read(byte[] b)方法

本文详细介绍了如何使用Java的FileInputStream类进行文件读取,包括read()和read(byte[]b)方法的具体应用,通过实例演示了如何从本地文件中读取字节数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 }

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

转载于:https://www.cnblogs.com/EarthPioneer/p/9359372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值