importjava.io.*;publicclassStringToInputStreamExample{publicstaticvoidmain(String[]args){Stringstr="Hello, World!";InputStreaminputStream=convertStringToInputStream(str);BufferedReaderreader=newBufferedReader(newInputStreamReader(inputStream));Stringline;try{while((line=reader.readLine())!=null){System....
importjava.io.InputStream;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.IOException;publicclassMain{publicstaticvoidmain(String[]args){StringtestString="Hello, World!\nWelcome to String to InputStream conversion.";InputStreaminputStream=StringToInputStreamConverter.convert(test...
String str = "String与InputStream相互转换"; InputStream in_nocode = new ByteArrayInputStream(str.getBytes()); InputStream in_withcode = new ByteArrayInputStream(str.getBytes("UTF-8")); 2.InputStream to String 这里提供几个方法。 方法1: public String convertStreamToString(InputStream is) { ...
1. UsingByteArrayInputStream UsingByteArrayInputStreamis the simplest way to createInputStreamfrom aString. Using this approach, we do not need any external dependency. Thestring.getBytes()method encodes theStringinto a sequence of bytes using the platform’s default charset. To use a different ch...
public String convertStreamToString(InputStream is) { // ??? } 一个很好的方法是使用Apache commonsIOUtils将InputStream复制到StringWriter… StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); ...
stringBuilder.append(new String(buffer,0, readBytes)); } System.out.println(stringBuilder.toString()); } } 缓冲区的大小自己根据实际来调,比 BufferedReader 还简洁些,不需管换行符的事情。 本文原始链接:http://unmi.cc/java-convert-inputstream-to-string, 来自:隔叶黄莺 Unmi Blog ...
Example: Convert InputStream to String import java.io.*; public class InputStreamString { public static void main(String[] args) throws IOException { InputStream stream = new ByteArrayInputStream("Hello there!".getBytes()); StringBuilder sb = new StringBuilder(); String line; BufferedReader br...
java.io.OutputStream;publicclassStringToFile{publicstaticvoidconvertToFileStream(String content, OutputStream outputStream)throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());byte[] buffer = newbyte[1024];int length;while ((length = inputStream.read(bu...
One effective way to convert anInputStreamto aStream<String>is by using aBufferedReaderalong with itslines()method. First, we’ll define abytearraybytescontaining a sequence of text lines: byte[] bytes = "Hello\nWorld\nThis\nis\na\ntest".getBytes(StandardCharsets.UTF_8); ...
然后,您可以使用IOUtils类将InputStream转换为String: 代码语言:java 复制 import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class InputStreamToString { public static void main(String[] args) { InputStrea...