Java面向对象之FileInputStream、FileOutputStream 及 FileReader 和 FileWriter

1、FileInputStream

1.1、结构继承关系图

在这里插入图片描述

1.2、FileInputStream 应用实例

要求:请使用 FileInputStream 读取 hello.txt 文件,并将文件内容显示到控制台

package inputstream_;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * FileInputStream 的使用(字节输入流 文件 --> 程序)
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }

    /**
     * 演示读取文件...
     * 单个字节的读取, 效率比较低
     */
    @Test
    public void readFile01() {
        String filePath = "e:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;

        try {
            // 创建 FileInputStream 对象, 用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取一个字节的数据, 如果没有输入可用, 此方法将阻止
            // 如果返回-1, 表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData);  // 转成 char 显示, hello.txt有中文会出现乱码问题
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流, 释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用 read(byte[] b) 读取文件, 提高效率
     */
    @Test
    public void readFile02() {
        String filePath = "e:\\hello.txt";
        // 字节数组
        byte[] buf = new byte[8];  // 一次读取 8 个字节
        int readLen = 0;
        FileInputStream fileInputStream = null;

        try {
            // 创建 FileInputStream 对象, 用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取最多 b.length 字节的数据到字节数组, 此方法将阻塞, 直到某些输入可用
            // 如果返回-1, 表示读取完毕
            // 如果读取正常, 返回实际读取的字节数
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));  // 显示, hello.txt有中文会出现乱码问题
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流, 释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2、FileOutputStream

2.1、结构继承关系图

在这里插入图片描述

2.2、FileOutputStream 应用实例 1

要求:请使用 FileOutputStream 在 a.txt 文件,中写入 “hello,world”,如果文件不存在,会创建文件(注意:前提是目录已经存在)

package outputstream_;

import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    /**
     * 演示使用 FileOutputStream 将数据写到文件中
     * 如果该文件不存在, 则创建该文件
     */
    @Test
    public void writeFile() {
        // 创建 FileOutputStream 对象
        String filePath = "e:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            // 得到 FileOutputStream 对象
            // 说明
            // 1. new FileOutputStream(filePath) 创建方式, 当写入内容时, 会覆盖原来的内容
            // 2. new FileOutputStream(filePath, true) 创建方式, 当写入内容时, 是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath, true);
            // 写入一个字节
            fileOutputStream.write('H');
            // 写入字符串
            String str = "allen, world!";
            // str.getBytes() 可以把 字符串 -> 字节数组
            fileOutputStream.write(str.getBytes());
        /*
            write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
        */
            fileOutputStream.write(str.getBytes(), 0, 5);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/*
a.txt文件内容:
Hallen, world!allen
*/
2.3、FileOutputStream 应用实例 2

要求:编程完成图片/音乐 的拷贝

package outputstream_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {
        // 完成 文件拷贝, 将 e:\\pic.jpg 拷贝 d:\\
        // 思路分析
        // 1. 创建文件的输入流, 将文件读入到程序
        // 2. 创建文件的输出流, 将读取到的文件数据, 写入到指定的文件
        String srcFilePath = "e:\\pic.jpg";
        String destFilePath = "d:\\pic.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            // 定义一个字节数组, 提高读取效果
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                // 读取到后, 就写入到文件 通过 fileOutputStream
                // 即, 是一边读, 一边写
                fileOutputStream.write(buf, 0, readLen);  // 一定要使用这个方法
            }
            System.out.println("拷贝 ok");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输入流和输出流, 释放资源
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3、FileReader 和 FileWriter

3.1、结构继承关系图

在这里插入图片描述

3.2、FileReader 相关方法

在这里插入图片描述

3.3、FileWriter 常用方法

在这里插入图片描述

3.4、FileReader 和 FileWriter 应用案例

使用 FileReader 从 story.txt 读取内容,并显示

package reader_;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) {

    }

    /**
     * 单个字符读取文件
     */
    @Test
    public void readFile01() {
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int data = 0;
        // 创建 FileReader 对象
        try {
            fileReader = new FileReader(filePath);
            // 循环读取 使用 read, 单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);  // 中文字符也可以正常读取
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 字符数组读取文件
     */
    @Test
    public void readFile02() {
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int readLen = 0;
        char[] buf = new char[8];

        try {
            // 创建 FileReader 对象
            fileReader = new FileReader(filePath);
            // 循环读取 使用 read(buf), 返回的是实际读取到的字符数
            // 如果返回-1, 说明到文件结束
            while ((readLen = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中,注意细节

package writer_;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "e:\\note.txt";
        // 创建 FileWriter 对象
        FileWriter fileWriter = null;
        char[] chars = {'a', 'b', 'c'};

        try {
            fileWriter = new FileWriter(filePath);  // 默认是覆盖写入
            // write(int): 写入单个字符
            fileWriter.write('H');
            // write(char[]): 写入指定数组
            fileWriter.write(chars);
            // write(char[],off,len): 写入指定数组的指定部分
            fileWriter.write("你好世界, java是全世界最好的语言".toCharArray(), 0, 4);
            // write(string): 写入整个字符串
            fileWriter.write("你好北京");
            fileWriter.write("风雨之后, 定见彩虹");
            // write(string,off,len): 写入字符串的指定部分
            fileWriter.write("上海天津", 0, 2);
            // 在数据量大的情况下, 可以使用循环操作
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 对应 FileWriter, 一定要关闭流 或者 flush 才能真正的把数据写入到文件
            // 源码
            /*
            private void writeBytes() throws IOException {
                this.bb.flip();
                int var1 = this.bb.limit();
                int var2 = this.bb.position();

                assert var2 <= var1;

                int var3 = var2 <= var1 ? var1 - var2 : 0;
                if (var3 > 0) {
                    if (this.ch != null) {
                        assert this.ch.write(this.bb) == var3 : var3;
                    } else {
                        this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
                    }
                }

                this.bb.clear();
            }
            */
            try {
                // fileWriter.flush();
                fileWriter.close();  // 关闭文件流, 等价 flush() + 关闭
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("程序结束...");
    }
}

/*
note.txt文件内容:
Habc你好世界你好北京风雨之后, 定见彩虹上海
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值