当前位置: 移动技术网 > IT编程>开发语言>Java > Java分享笔记:FileInputStream流的 read()方法 和 read(byte[] b)方法

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

2018年07月24日  | 移动技术网IT编程  | 我要评论
 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 }

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网