1、FileInputStream概念 FileInputStream流被称为文件字节输入流,意思指对文件数据以字节的形式进行读取操作如读取图片视频等; 2、我们看JDK对FileInputStream描述 3、构造方法摘要 1、FileInputStream(File file):通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。 2、FileInputStream(FileDescriptor fdObj)创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。 3、FileInputStream(String name)通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。 4、通过FileInputStream读取D盘中的 hi.txt 文件/**
第一种方式:使用 read()方法
1、read()方法每次只读取一个字节
2、read()方法返回值是一个int类型,代码该字符的int值
3、如果返回值为-1,说明读取完毕
*/
public class $Test03 {
public static void main(String[] args) throws Exception {
String path = "D:\\hi.txt";
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
int resultData;
while ((resultData = inputStream.read()) != -1) {
System.out.print((char)resultData);
}
} catch (Exception e) {
// TODO: handle exception
}finally {
inputStream.close();
}
}
}
/**
使用read(byte[] b)方法读取文件
1、byte[] b = new byte[3];代表一次性去读三个字节方法b数组中
2、read(byte[] b)方法的返回值是读取的字节的长度
*/
public static void main(String[] args) throws Exception {
String path = "D:\\hi.txt";
InputStream inputStream = null;
byte[] b = new byte[3];
try {
inputStream = new FileInputStream(path);
int resultLength;
while ((resultLength = inputStream.read(b)) != -1) {
System.out.print(new String(b , 0 , resultLength));
}
} catch (Exception e) {
// TODO: handle exception
}finally {
inputStream.close();
}
}
}