<导航

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 @ 2022-04-16 11:49  字节悦动  阅读(2076)  评论(0编辑  收藏  举报