目录
2.3 应用实例:请使用FileInputStream读取 hello.txt 文件,并将文件内容显示到控制台

FileInputStream ,该文件由文件系统中的 File对象 file命名。FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。FileInputStream ,该文件由文件系统中的路径名 name命名。
在D盘新建一个 hello.txt 文件


2.3.1 使用read()方法读取

- public class FileInputStream01 {
- public static void main(String[] args) {
-
- }
- @Test
- public void readFile01(){
- String filePath = "D:\\hello.txt";
- int readData = 0;
- FileInputStream fileInputStream = null;
- try {
- //创建 FileInputStream 对象,用于读取文件
- fileInputStream = new FileInputStream(filePath);
- //如果返回-1,表示读取完毕
- while ((readData = fileInputStream.read()) != -1){
- //转成char显示
- System.out.print((char)readData);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- //关闭文件流,释放资源
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }

2.3.2 使用 read(byte[] b) 方法读取

- public class FileInputStream01 {
- public static void main(String[] args) {
-
- }
- @Test
- public void readFile02(){
- String filePath = "D:\\hello.txt";
- int readlen = 0;
- //字节数组,一次读取8个字节
- byte[] buf = new byte[8];
- FileInputStream fileInputStream = null;
- try {
- //创建 FileInputStream 对象,用于读取文件
- fileInputStream = new FileInputStream(filePath);
- //如果返回-1,表示读取完毕
- //如果读取正常,返回实际读取的字节数
- while ((readlen = fileInputStream.read(buf)) != -1){
- //转成字符串
- System.out.print(new String(buf,0,readlen));
- }
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- //关闭文件流,释放资源
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
