public String getContent(final URL url) { try { InputStream inputStream = url.openStream(); return new Scanner(inputStream).useDelimiter("\\A").next(); } catch (final Exception e) { } return ""; } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11....
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...
InputStream source = new URL("http://pat.net/misc/foo.txt").openStream(); The canonical way to gather it to a String has always been to use a BufferedReader, e.g. BufferedReader br = new BufferedReader( new InputStreamReader( source ) ); StringBuffer text = new StringBuffer(); fo...
获取InputStream 并将其转换为String的简单方法。 添加commons-io-2.4.jar import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils;publicclassStringFromFile {publicstaticvoidmain(String[] args) throws IOException { InputStream inputStream= StringFromFile.class.getReso...
3. ConvertingInputStreamto Base64 String Java has built-in support for Base64 encoding and decoding in thejava.util.Base64class. So we’ll be using thestaticmethods from there to do the heavy lifting. Base64.encode()method expects abytearray, and our image is in a file. Therefore, we ...
Stream<String> stringStream = scanner.findAll(".+") .map(MatchResult::group); String result = stringStream.collect(Collectors.joining()); assertEquals("HelloWorldThisisatest", result); } } In this approach, we initialize aScannerobject with theInputStreamand configure it to use UTF-8 encoding...
1. UsingInputStream.readAllBytes()(Since Java 9) TheInputStream.readAllBytes()API converts the input stream to bytes. Then we use thenew String()to create a newStringobject. InputStreamin=newFileInputStream(newFile("C:/temp/test.txt"));StringfileContent=newString(in.readAllBytes()); ...
How do I convert an InputStream to a string in Java?Brian L. Gorman
If you have ajava.io.InputStreamobject, how should you process that object and produce aString? Suppose I have anInputStreamthat contains text data, and I want to convert it to aString, so for example I can write that to a log file.PartyCity Feedback ...
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...