- How to convert String to InputStream in Java
- How to convert String to InputStream in Java
- 1. Convert String to InputStream in Java
- 2. Convert String to InputStream Using Apache IOUtils
- 3. Convert String to InputStream Guava.
- Summary
- How to Convert String to InputStream
- 2. Convert String to InputStream using ByteArrayInputStream
- 3. Using Guava to convert String to InputStream
- 4. Converting String to InputStream using IOUtils from Apache Commons IO
- 5. Conclusion
- Convert String to InputStream in Java
- Строка Java в поток ввода
- 1. Обзор
- 2. Преобразование С Помощью Простой Java
- 3. Преобразование С Помощью Гуавы
- 4. Преобразование С помощью Commons IO
- 5. Заключение
- Читайте ещё по теме:
How to convert String to InputStream in Java
In the previous tutorial, we discussed how can we convert an InputStream into a String . In this tutorial we are going to see the opposite direction. So, we are going to covert a String into an InputStream . When you have a very big String that you want to process it incrementally, or a small portion of it at a time, converting it to an InputStream can be very helpful. In the previous tutorials what we actually did was to read the bytes from an input stream and append them to a String variable. In this tutorial we’re going to do the same technique.
- Get the bytes of the String
- Create a new ByteArrayInputStream using the bytes of the String
- Assign the ByteArrayInputStream object to an InputStream variable (which you can do as InputStream is a superclass of ByteArrayInputStream )
package com.javacodegeeks.java.core; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class StringToInputStream < public static void main(String[] args) throws IOException < String string = "This is a String.\nWe are going to convert it to InputStream.\n" + "Greetings from JavaCodeGeeks!"; //use ByteArrayInputStream to get the bytes of the String and convert them to InputStream. InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8"))); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String output = bufferedReader.readLine(); while (output != null) < System.out.println(output); output = bufferedReader.readLine(); >> >
This is a String. We are going to convert it to InputStream. Greetings from JavaCodeGeeks!
This was an example of how to convert String to InputStream in Java.
How to convert String to InputStream in Java
In this post, we will go through different options at how to convert String to InputStream in Java using JDK and Other utility classes.
1. Convert String to InputStream in Java
Let’s take a look at the converting String to InputStream using pure Java. We will be using the ByteArrayInputStream to convert String to InputStream.
public class StringToIOJava < public static void main(String[] args) throws IOException < String inputString = "This is a String to demo as how to convert it to input stream using Core Java API"; //String to input stream try (InputStream inputStream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)) ) < String content; while ((content = bufferedReader.readLine()) != null) < //work with file >> > >
It’s always recommended to pass explicit Charset to the method getBytes() to avoid any unwanted behavior.Java will pick platform’s default char-set if not passed to the method.If you are on older version of JDK (Less than 7), make sure to replace StandardCharsets.UTF_8 with «UTF-8» .
If you like you can also work on a more simpler version if you want to use the stream for something else.
import java.io.ByteArrayInputStream; import java.io.InputStream; public class ConvertStringToInputStream < public static void main(String[] args) < String inputString = "This is a String to demo as how to convert it to input stream using Core Java API"; InputStream stream = new ByteArrayInputStream(inputString.getBytes()); //work with your input stream >>
Let’s understand few basic while converting the String to InputStream in Java:
- We are passing the byte array to the ByteArrayInputStream .
- The getByte() method encode the String using platform default charset (if no explicit charset is passed).
- The getByte() method also provide option to pass the charset using getByte(Charset charset) . This is useful when we know the charset of the String and want to control the encoding process.
2. Convert String to InputStream Using Apache IOUtils
Apache Commons IO provides provide a lot of convenient method while working on I/O operations in Java.If you are working on a larger application, there are high level of chances that it’s already part of the required dependencies. Also the IOUtils.toInputStream is more readable. Here are the list of overloaded method available in the API.
- IOUtils.toInputStream(CharSequence input, Charset encoding)
- IOUtils.toInputStream(CharSequence input, String encoding)
- IOUtils.toInputStream(String input, Charset encoding)
- IOUtils.toInputStream(String input, String encoding)
I am not including the deprecated methods.Let’s see how to use the IOUtils to perform these operations.
public class StringToIOApache < public static void main(String[] args) throws IOException < String inputString = "This is a String to demo as how to convert it to input stream using Apache Commons IO"; InputStream inputStream = IOUtils.toInputStream(inputString, StandardCharsets.UTF_8); >>
Make sure you include the jar as dependency.If you are using the Maven/Gradle, add the dependency in the pom.xml or Gradle configuration file.
commons-io commons-io add latest version
3. Convert String to InputStream Guava.
If your project using the Google Guava library, it also provides an option to convert String to InputStream in Java.Let’s see how to do this with Guava. If your project is not using it and you like to try , make sure you add the required dependencies either directly or using the Maven or Gradle as your build platform.
import java.io.IOException; import java.io.InputStream; import com.google.common.base.Charsets; import com.google.common.io.CharSource; public class ConvertStringToInputStream < public static void main(String[] args) < String inputString = "This is a String to demo as how to convert it to input stream using Core Java API"; /** Convert using Google Guava */ InputStream stream = new ReaderInputStream(CharSource .wrap(str) .openStream(), Charsets.UTF_8); >>
com.google.guava guava latest version
Summary
In this post, we saw how to convert String to InputStream in Java. We can use the JDK method to convert String to InputStream, Apache IOUtils or the Google Guava API to perform the conversion.If you want to convert InputStream to String in Java, please read out article on Convert InputStream to String in Java.
How to Convert String to InputStream
In this tutorial we are going to look at how to convert String to InputStream in Java. We will present solutions in plain Java and will use external libraries like Guava and Apache Commons IO .
For more Java I/O related articles, check the following links:
2. Convert String to InputStream using ByteArrayInputStream
The solution in plain Java is almost straightforward and, which is also important, we can achieve a wanted result without additional dependencies.
The following example shows how to use ByteArrayInputStream to convert String to InputStream:
package com.frontbackend.java.io.conversions.string.toinputstream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class StringToInputStreamUsingByteArrayInputStream < public static void main(String[] args) < String str = "frontbackend.com"; InputStream result = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)); >>
In this example first, we get bytes representing the String encoded using UTF-8 charset. Then, we create ByteArrayInputStream instance that takes byte array as a constructor parameter.
Note that we should always provide the encoding of the given string unless the encoding matches the default platform charset.
3. Using Guava to convert String to InputStream
With Guava we can also achieve conversions from String to InputStream, however, the solution is more complex:
package com.frontbackend.java.io.conversions.string.toinputstream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.input.ReaderInputStream; import com.google.common.base.Charsets; import com.google.common.io.CharSource; public class StringToInputStreamUsingGuava < public static void main(String[] args) throws IOException < String str = "frontbackend.com"; InputStream result = new ReaderInputStream(CharSource.wrap(str) .openStream(), Charsets.UTF_8); >>
First, we are creating Reader object using CharSource.wrap(str).openStream() method. Then, we used ReaderInputStream to convert Reader to the InputStream .
Note that using ReaderInputStream constructor without a charset as a second parameter (charset) is deprecated now.
4. Converting String to InputStream using IOUtils from Apache Commons IO
Using IOUtils class from Apache Commons IO gives us a pretty straightforward solution:
package com.frontbackend.java.io.conversions.string.toinputstream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; public class StringToInputStreamUsingIOUtils < public static void main(String[] args) throws IOException < String str = "frontbackend.com"; InputStream stream = IOUtils.toInputStream(str, StandardCharsets.UTF_8); >>
Here we have dedicated method IOUtils.toInputStream that do the conversion transparently.
Note that using IOUtils.toInputStream(str) with a single parameter is deprecated. Now we need to explicitly specify the encoding of the String as a second parameter.
5. Conclusion
In this article, we illustrated several methods to convert String to InputStream in Java. The important knowledge to remember is when we convert String to the byte stream we should always provide the encoding.
If you are looking for reverse method, that converts InputStream to a String check the following: InputStream -> String
As usual, code use in this article is available under our GitHub repository.
Convert String to InputStream in Java
Learn to convert a String into InputStream using ByteArrayInputStream and IOUtils classes. Writing String to Steam is a frequent job in Java and having a couple of good shortcuts will prove useful.
1. Using ByteArrayInputStream
Using ByteArrayInputStream is the simplest way to create InputStream from a String. Using this approach, we do not need any external dependency.
The string.getBytes() method encodes the String into a sequence of bytes using the platform’s default charset. To use a different charset, use the method getBytes(Charset charset) .
The StandardCharsets class provides the constant definitions for the standard charsets. For example, StandardCharsets.UTF_8 .
String string = "howtodoinjava.com"; InputStream instream = new ByteArrayInputStream(string.getBytes());
IOUtils is a very useful class for IO operations. This solution is also pretty good because apache commons is very much a mostly included jar in most applications.
IOUtils.toInputStream() makes code very much readable. It is an overloaded method so use the desired encoding while invoking this method.
static InputStream toInputStream(String input, Charset encoding) static InputStream toInputStream(String input, String encoding)
Given program demonstrates how to create InputStream from a String.
String string = "howtodoinjava.com"; InputStream inStream = IOUtils.toInputStream(string, StandardCharsets.UTF_8);
Строка Java в поток ввода
Как преобразовать строку в входной поток, используя обычную Java, Guava или Commons IO.
1. Обзор
В этом кратком руководстве мы рассмотрим, как преобразовать стандартную строку в InputStream , используя обычную Java, Guava и библиотеку ввода-вывода Apache Commons.
Эта статья является частью серии “Java – Back to Basic” здесь, на Baeldung.
2. Преобразование С Помощью Простой Java
Давайте начнем с простого примера использования Java для выполнения преобразования – с использованием промежуточного байта массива:
@Test public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect() throws IOException
Обратите внимание, что метод getBytes() кодирует эту Строку , используя кодировку платформы по умолчанию, поэтому, чтобы избежать нежелательного поведения, вы можете использовать getBytes(Charset charset) и контролировать процесс кодирования .
3. Преобразование С Помощью Гуавы
Guava не предоставляет прямого метода преобразования, но позволяет нам получить CharSource из Strong и легко преобразовать его в ByteSource . Затем легко получить InputStream :
@Test public void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException
Однако обратите внимание, что метод asByteSource помечен как @Beta . Это означает, что он может быть удален в будущем выпуске гуавы. Мы должны иметь это в виду.
4. Преобразование С помощью Commons IO
Наконец, библиотека ввода-вывода Apache Commons предоставляет отличное прямое решение:
@Test public void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect() throws IOException
Наконец, обратите внимание, что в этих примерах мы оставляем входной поток открытым – не забудьте закрыть его, когда закончите .
5. Заключение
В этой статье мы представили три простых и кратких способа получения InputStream из простой строки.
Как всегда, полный исходный код доступен на GitHub .