概述
在開發過程中,你肯定遇到過從流中解析數據,或者把數據寫入流中,或者輸入流轉換為輸出流,而且最后還要進行流的關閉,原始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