>

org.apache.commons.io.IOUtils

概述

  在开发过程中,你肯定遇到过从流中解析数据,或者把数据写入流中,或者输入流转换为输出流,而且最后还要进行流的关闭,原始jdk自带的方法写起来太复杂,还要注意各种异常,如果你为此感到烦恼,那IOUtils可以让我们优雅的操作流。

使用

官网地址https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

首先,引入dependency

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
</dependency>

实现文件复制

复制代码
import org.apache.commons.io.IOUtils;

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;

        fileInputStream = new FileInputStream("D://uploadanddownload-0.0.1-SNAPSHOT.jar");
        File file = new File("D://a/b");
        file.mkdirs();
        fileOutputStream=new FileOutputStream("D://a/b/uploadanddownload-0.0.1-SNAPSHOT.jar");

        IOUtils.copy(fileInputStream,fileOutputStream);
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(fileOutputStream);


    }
}
复制代码

从流中读取数据

FileInputStream fileInputStream = new FileInputStream(new File("d://demo.txt"));
List<String> list = IOUtils.readLines(fileInputStream, "UTF-8");//只要是InputStream流都可以,比如http响应的流
//直接把流读取为String
String content = IOUtils.toString(inputStream,"UTF-8");
//把流转换为byte数组
byte[] bytes = IOUtils.toByteArray(inputStream);

把数据写入流

//把数据写入输出流
IOUtils.write(jsonStr, outputStream);
//把字符串转换流
InputStream inputStream = IOUtils.toInputStream(jsonStr, "UTF-8");

流的相互复制

IOUtils.copy(inputstream,outputstream);
IOUtils.copy(inputstream,writer);
IOUtils.copy(inputstream,writer,encoding);
IOUtils.copy(reader,outputstream);
IOUtils.copy(reader,writer);
IOUtils.copy(reader,writer,encoding);

流的关闭

复制代码
try {
     return IOUtils.copy(inputStream, outputStream);
 } finally {
     //优雅的关闭流
     IOUtils.closeQuietly(inputStream);
     IOUtils.closeQuietly(outputStream);
     //打印关闭异常
     //IOUtils.closeQuietly(outputStream, ex -> log.error("关闭资源异常: {}", ex.getMessage()));
}
复制代码

 

 

参考文章:

https://www.jianshu.com/p/6b4f9e5e2f8e

posted @   字节悦动  阅读(2902)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示

目录导航