How to convert Java String to InputStream ?

InputStream is a super class of all classes representing an input stream of bytes. Here is one example to convert a String to InputStream.

Example

package com.pretech;
import java.io.*;
public class StringtoInputStream {
	public static void main(String[] args) throws IOException {
		//Converting
		InputStream ins = new ByteArrayInputStream("HelloWorld".getBytes());
		
		//Reading
		BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
		String line;
		
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
	}
}

Output



HelloWorld


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts