在Java中,我们可以使用ByteArrayInputStream
或IOUtils
将String
转换为InputStream
1.纯Java – ByteArrayOutputStream
InputStream result = new ByteArrayInputStream(anyString.getBytes(StandardCharsets.UTF_8));
2. Apache Commons IO – IOUtils.toInputStream
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
InputStream result = IOUtils.toInputStream(anyString, StandardCharsets.UTF_8);
注意
阅读此书将InputStream转换为String
1.将字符串转换为InputStream
StringToInputStream.java
package com.mkyong;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class StringToInputStream {
public static void main(String[] args) {
String name = "mkyong";
InputStream inputStream = convertStringToInputStream(name);
// do something about the inputStream
}
// String -> InputStream
private static InputStream convertStringToInputStream(String name) {
InputStream result = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8));
return result;
}
// commons-io
private static InputStream convertStringToInputStreamCommonIO(String name) {
InputStream result = IOUtils.toInputStream(name, StandardCharsets.UTF_8);
return result;
}
}
参考文献
翻译自: https://mkyong.com/java/how-to-convert-string-to-inputstream-in-java/