Java中Reader和为InputStream互相转换

IT 文章2年前 (2023)发布 小编
0 0 0

在这个简短的Java IO教程中,我们将学习如何将Reader转换为InputStream,以及如何将InputStream转换为Reader。请注意,Reader用于读取字符,而InputStream用于读取原始字节。两者设计目的不同,因此在使用它们时请小心。

1.将Reader转换为InputStream

Reader通常持有字符数据,通常是字符串或字符数组。如果我们有权访问String或char[],则可以直接从中获取InputStream。

try(InputStream inputStream = new ByteArrayInputStream(
    content.getBytes(StandardCharsets.UTF_8))){
  //Use InputStream
}

如果我们有对现有Reader的引用,则可以使用以下技术获取InputStream。

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

1.1Reader -> byte[] -> InputStream

我们从Reader获取内容到byte[],然后使用byte[]创建InputStream。这种转换过程可以通过多种方式实现,并使用不同的库。例如,让我们从原生IO API开始。

try(Reader reader = new BufferedReader(
    new StringReader(content))){
  char[] charBuffer = new char[8 * 1024];
  int numCharsRead;
  while ((numCharsRead = reader.read(charBuffer, 0,
      charBuffer.length)) != -1) {
    builder.append(charBuffer, 0, numCharsRead);
  }
}
try(InputStream inputStream = new ByteArrayInputStream(
	builder.toString().getBytes(StandardCharsets.UTF_8))){
  //Use InputStream
}

同样,我们可以使用Common IO的IOUtils.toString(reader)类从Reader读取内容到String。

String content = "Hello world";
try(Reader reader = new BufferedReader(new StringReader(content));
InputStream inputStream = IOUtils.toInputStream(IOUtils.toString(reader), Charsets.UTF_8);) {
	//Use InputStream
}

我们还可以使用Guava的CharStreams.toString(reader)类与前一个解决方案类似。

try(
    Reader reader = new BufferedReader(new StringReader(content));
    InputStream inputStream = new ByteArrayInputStream(
      CharStreams.toString(reader).getBytes(StandardCharsets.UTF_8))){
  //Use InputStream
}

1.2. Commons IO的ReaderInputStream

ReaderInputStream是InputStream的实现在读取字符流时不需要将底层的Reader包装在BufferedReader中。

ad

AI 工具导航

优网导航旗下AI工具导航,精选全球千款优质 AI 工具集

所有的read()操作都进行了缓冲,因此不需要将底层的Reader包装在BufferedReader中。

try(Reader reader = new StringReader("Hello world");
    InputStream inputStream = new ReaderInputStream(reader, StandardCharsets.UTF_8);){
  //Use inputStream
}

2.将InputStream转换为Reader

Java有InputStreamReader,它的设计目的就是做这个。这个类充当字节流到字符流的桥梁。

为了获得最高的效率,考虑将InputStreamReader包装在BufferedReader中。

InputStream inputStream = new ByteArrayInputStream("Hello world".getBytes());
Reader reader = new BufferedReader(new InputStreamReader(inputStream));

3.结论

在这个Java IO教程中,我们学习了如何使用简单易懂的示例在Reader和InputStream之间进行转换。

© 版权声明

相关文章

暂无评论

暂无评论...