In Java, we can use ByteArrayInputStream
to convert a String
to an InputStream
.
String str = "tuts.heomi.net";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
1. ByteArrayInputStream
This example uses ByteArrayInputStream
to convert a String
to an InputStream
and saves it into a file.
ConvertStringToInputStream.java
package com.favtuts.string; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; public class ConvertStringToInputStream { public static final int DEFAULT_BUFFER_SIZE = 8192; public static void main(String[] args) throws IOException { String name = "tuts.heomi.net"; // String to InputStream InputStream is = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8)); // current directory Path cwd = Path.of("").toAbsolutePath(); String filePath = cwd.toString() + "/file.txt"; // save to a file save(is, filePath); } // save the InputStream to a File private static void save(final InputStream is, final String fileName) throws IOException { // read bytes from InputStream and write it to FileOutputStream try (FileOutputStream outputStream = new FileOutputStream(new File(fileName), false)) { int read; byte[] bytes = new byte[DEFAULT_BUFFER_SIZE]; while ((read = is.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } } }
2. Apache Commons IO – IOUtils
This example uses commons-io
library, IOUtils.toInputStream
API to convert String
to InputStream
.
pom.xml
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency>
import org.apache.commons.io.IOUtils; // String to InputStream InputStream result = IOUtils.toInputStream(str, StandardCharsets.UTF_8);
Review the source code of IOUtils.toInputStream
, it is using the same ByteArrayInputStream
to convert a String
to an InputStream
.
package org.apache.commons.io; public class IOUtils { public static InputStream toInputStream(final String input, final Charset charset) { return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(charset))); } //... }
Further Reading
Convert InputStream to String in Java
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-string