1、
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/*由于InputStream是抽象类,不能实例化,故在实际开发中一般使用其子实现类FileInputStream进行实例化
* FileInputStram的一些方法:
* read() :从此输入流中读取一个数据字节。
* read(byte[] b):从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
read(byte[] b, int off, int len) : 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中
*
* */
public class IO_InputStream_FileInputStream_method {
public static void main(String[] args) throws Exception {
// 首先在本项目目录下创建f.txt文件,文件内容为asdfgh
// 创建一个字节文件输入流对象
// 读取文件
FileInputStream f = new FileInputStream("f.txt");
// 判断
// read() :从此输入流中读取一个数据字节。
int by = 0;
while ((by = f.read()) != -1) {
System.out.print((char) by); // asdfgh
}
// 释放资源
f.close();
}
}
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IO_InputStream_FileInputStream_method2 {
public static void main(String[] args) throws Exception {
// 创建文件输入流对象
FileInputStream f = new FileInputStream("f.txt");
// read(byte[] b, int off, int len) : 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中
byte[] bytes = new byte[1024]; // 此处空间大小为1024或者1024的整数倍
int length = 0;
while ((length = f.read(bytes)) != -1) { // 判断,赋值,循环
System.out.println(new String(bytes, 0, length)); // 带上len的用法 //输出:asdfgh
}
}
}