Java 输入输出流总结

1. 运用BufferedInputStream 读取文件流和BufferedOutputStream写文件流:

复制代码
protected static void writeFile2(String inputPath, String outputPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(inputPath));
            bos = new BufferedOutputStream(new FileOutputStream(outputPath));
            int buffer = 1024 * 1024;
            byte[] data = new byte[buffer];
            int len;
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
            }
        }
    }
复制代码

2. BufferedReader 读取文件流和BufferedWriter写文件流:

复制代码
protected static String readFile(String inputPath) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(
                    inputPath)));
            StringBuffer result = new StringBuffer();
            String lineString = null;
            while ((lineString = br.readLine()) != null) {
                result.append(lineString);
                result.append("\n");
            }
            return result.toString();

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
            }
        }

    }
复制代码
复制代码
protected static void writeFile(String inputString, String outputPath)
            {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(outputPath));
            bw.write(inputString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
            }
        }
    }
复制代码
posted @   风过无痕的博客  阅读(260)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示