本文我们介绍StreamUtils类使用。StreamUtils是spring中用于处理流的类,是java.io包中inputStream和outputStream,不是java8中Steam。使用时仅依赖spring-core,主要需要了解几个静态方法。

拷贝Stream

StreamUtils类包括几个重载copy()方法,也包括几个变体:

  • copyRange()
  • copyToByteArray()
  • copyString()

我们能不依赖任何jar实现拷贝流。然而,这样会使代码冗难读,不易理解。

为了简单起见,我们省略关闭流,实际应用中需要调用close()方法关闭输入或输出流。

让我们看看如何拷贝inputStream内容至outputStream:

@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFile); StreamUtils.copy(in, out); assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(inputFileContent, outputFileContent);
}

创建的新文件包括inputStream中的内容。

其中getStringFromInputStream() 方法负责取inputStream内容并返回字符串。

import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter; public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
} public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}

我们也可以不拷贝inputStream全部内容,可以使用copyRange()方法仅拷贝一定范围的内容至outputStream.

@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName); StreamUtils.copyRange(in, out, 1, 10); assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}

如上述代码所示,copyRange方法有四个参数,inputStream,outputStream,开始拷贝位置,结束拷贝位置。如果我们指定的长度超过inputStream的长度呢?copyRange方法仅拷贝至流的结尾。

下面看看如何拷贝字符串至outputStream:

@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt"); StreamUtils.copy(string, StandardCharsets.UTF_8, out); assertTrue(outputFile.exists()); String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); assertEquals(outputFileContent, string);
}

copy方法带三个参数:被拷贝的字符串,写文件时指定的字符集,指定目的地(outputStream)。

我们也可以把给定的inputStream内容拷贝为字符串:

@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
assertEquals(inputFileContent, content);
}

也可以拷贝字节数组的内容至outputStream:

public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt"); StreamUtils.copy(byteArray, out); String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); assertEquals(outputFileContent, string);
}

同样,也可以拷贝inputStream内容至字节数组:

public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(is); String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); assertEquals(inputFileContent, content);
}

其他功能

inputStream可以作为参数传递给drain()方法,删除流中所有剩余数据:

StreamUtils.drain(in);

也可以使用emptyInput()方法获得一个有效空输入流:

public InputStream getInputStream() {
return StreamUtils.emptyInput();
}

还有两个重载方法nonClosing(),inputStream和outputStream流可以作为参数,用于返回无需关闭的inputStream和outputStream流。

public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}

总结

本文介绍了StreamUtil类及其所有方法,利用可以大大简单代码,提高开发效率。

Spring 中StreamUtils教程的更多相关文章

  1. Spring中如何动态注入Bean实例教程

    前言 在Spring中提供了非常多的方式注入实例,但是由于在初始化顺序的不同,基于标注的注入方式,容易出现未被正确注入成功的情况. 本文将介绍一种在实际项目中基于动态的方式来提取Spring管理的Be ...

  2. Spring Boot2 系列教程(十三)Spring Boot 中的全局异常处理

    在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @ControllerAdvice 来统一处理,也可以自己来定义异常处理方案.Spring Boot 中,对异常的处理有 ...

  3. Spring 事务传递教程_有实例

    通过这篇文章,你将学习到Spring框架中中事务的传递 简介 在处理Spring管理的事务时,开发人员可以以传播的方式定义事务的行为.换句话说,开发人员能够决定业务方法如何被封装在逻辑和物理事务中.来 ...

  4. Spring Data Solr教程(翻译) 开源的搜索服务器

    Solr是一个使用开源的搜索服务器,它采用Lucene Core的索引和搜索功能构建,它可以用于几乎所有的编程语言实现可扩展的搜索引擎. Solr的虽然有很多优点,建立开发环境是不是其中之一.此博客条 ...

  5. Spring MVC 入门教程示例 (一)

    今天和大家分享下  Spring MVC  入门教程 首先还是从 HelloWorld  web 工程开始 -------------------------- 1.首先创建一个Maven Web工程 ...

  6. Spring中@Transactional事务回滚实例及源码

    一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用.下面举个栗子:比如一个部门里面有很多成员,这两者分别保存在部门表和成员表里面,在删除 ...

  7. Spring Data JPA教程, 第三部分: Custom Queries with Query Methods(翻译)

    在本人的Spring Data JPA教程的第二部分描述了如何用Spring Data JPA创建一个简单的CRUD应用,本博文将描述如何在Spring Data JPA中使用query方法创建自定义 ...

  8. Spring Data Solr教程(翻译)

    大多数应用都必须具有某种搜索功能,问题是搜索功能往往是巨大的资源消耗并且它们由于沉重的数据库加载而拖垮你的应用的性能 这就是为什么转移负载到一个外部的搜索服务器是一个不错的主意,Apache Solr ...

  9. Spring Data JPA教程, 第二部分: CRUD(翻译)

    我的Spring Data Jpa教程的第一部分描述了,如何配置Spring Data JPA,本博文进一步描述怎样使用Spring Data JPA创建一个简单的CRUD应用.该应用要求如下: pe ...

随机推荐

  1. MFC点击控件拖动窗口

    void CMouseClickDlg::OnLButtonDown(UINT nFlags, CPoint point) { CDialogEx::OnLButtonDown(nFlags, poi ...

  2. 多核cpu的特殊中断

    cpu可以向其他cpu发送中断,也可以向单独某一个cpu发送中断 每个 cpu 都有一个时钟中断源

  3. sql partition by

    --不分班按学生成绩排名 select *,ROW_NUMBER() over(order by Score desc) as Sequence from Student id          Gr ...

  4. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---2

    以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下: <Linux命令行与shell脚本 ...

  5. VIM使用技巧4

    使移动和修改都能重复,对重复的操作能够回退比能够重复更加重要: 目的操作重复回退序号 执行修改{edit}.u1 在行内查找下一个指定字符 f{char}/t{char};,2 在行内查找上一个指定字 ...

  6. Cryptography I 学习笔记 --- 认证加密

    1. 认证加密,Alice与Bob共享一个密钥k,Alice可以发送密文E给Bob,Bob可以确定接收到的E一定是拥有密钥k的Alice产生的.而不是攻击者随便产生的. 2. 认证加密必须能抵挡住选择 ...

  7. querySelector和getElementById之间的区别

    一.概述 今天在看js的时候发现里面的代码基本上都是用querySelector()和querySelectorAll()来获取元素,就有点疑惑为什么不用getElementById(),可能也是因为 ...

  8. Aizu 2300 Calender Colors dfs

    原题链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2300 题意: 给你一个图,让你生成一个完全子图.使得这个子图中每个点的最 ...

  9. IIS 7 Access to the path ‘c:\windows\system32\inetsrv\’ is denied

    https://randypaulo.wordpress.com/2011/09/13/iis-7-access-to-the-path-cwindowssystem32inetsrv-isdenie ...

  10. iOS进行单元测试OCUnit+xctool

    单元测试 什么是单元测试 wiki解释 简单说来就是为你的方法多专门写一个测试函数.以保证你的方法在不停的修改开发中.保持正确.如果出错,第一时间让你知道,这样从最小单位开始监控来保证软件的质量. 我 ...