Today we will look into how to convert String to InputStream in java. Recently I wrote a post to convert InputStream to String.
今天,我们将研究如何在Java中将String转换为InputStream。 最近,我写了一篇文章将InputStream转换为String 。
Java String to InputStream (Java String to InputStream)
There are two ways that I have used to convert String to InputStream.
我曾经用两种方法将String转换为InputStream。
- Java IO ByteArrayInputStream class Java IO ByteArrayInputStream类
- Apache Commons IO IOUtils class Apache Commons IO IOUtils类
Let’s have a look at example program to use these classes.
让我们看一下使用这些类的示例程序。
使用ByteArrayInputStream将Java字符串转换为InputStream (Java String to InputStream using ByteArrayInputStream)
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 StringToInputStreamUsingByteArrayInputStream {
public static void main(String[] args) throws IOException {
String str = "convert String to Input Stream Example using ByteArrayInputStream";
// convert using ByteArrayInputStream
InputStream is = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
// print it to console
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
}
}
使用Apache Commons IOUtils将字符串转换为InputStream (String to InputStream using Apache Commons IOUtils)
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
public class StringToInputStreamUsingIOUtils {
public static void main(String[] args) throws IOException {
String str = "Example using Apache Commons IO class IOUtils";
InputStream stream = IOUtils.toInputStream(str, Charset.forName("UTF-8"));
stream.close();
}
}
You can use IOUtils
if you are already using Apache Commons IO jars, otherwise there is no benefit since internally it’s using ByteArrayInputStream class. Below is the toInputStream
method implementation from IOUtils
class source code.
如果您已经在使用Apache Commons IO jar,则可以使用IOUtils
,否则没有任何好处,因为它在内部使用ByteArrayInputStream类。 下面是IOUtils
类源代码的toInputStream
方法实现。
public static InputStream toInputStream(final String input, final Charset encoding) {
return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding)));
}
That’s all about converting String to Input Stream in java.
这就是在Java中将String转换为Input Stream的全部内容。
翻译自: https://www.journaldev.com/738/java-string-to-inputstream