Java基础知识强化之IO流笔记21:FileInputStream读取数据
1. 字节输入流的操作步骤:
(1)创建字节输入流的对象
(2)调用read()方法读取数据,并把数据显示到控制台
(3)关闭字节输入流的对象资源
2. FileInputStream构造:
FileInputStream(File file) Constructs a new FileInputStream based on
file . |
FileInputStream(FileDescriptor fd)
Constructs a new FileInputStream on the FileDescriptor
fd . |
FileInputStream(String fileName)
Constructs a new FileInputStream on the file named
fileName . |
3. 代码示例:
1 package com.himi.fileinputstream; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 /* 7 * 读取数据的方式: 8 * int read():一次读取一个字节 9 * int read(byte[] b):一个读取一个字节数组 10 */ 11 public class FileInputStreamDemo { 12 13 public static void main(String[] args) throws IOException { 14 // FileInputStream(String name) 15 //创建字节输入流对象 16 FileInputStream fis = new FileInputStream("fis.txt"); 17 18 19 //调用read()方法读取数据,并把数据显示在控制台 20 int by = 0; 21 while((by = fis.read())!= -1) { 22 System.out.print((char) by); 23 } 24 //释放资源 25 fis.close(); 26 27 } 28 29 }
运行效果如下: