Java – Convert String to InputStream

If you want to convert a String into InputStream, you can use the following piece of code.

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

public class ConvertStringToInputStream {

	public static void main(String[] args) {
		try {
			// Convert the String into InputStream 
			String eurekaUrl = "https://ykyuen.wordpress.com";
			InputStream is = new ByteArrayInputStream(eurekaUrl.getBytes("UTF-8"));
			
			// Use Apache Commons IO to get the content of the InputStream
			System.out.println(IOUtils.toString(is, "UTF-8")); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


 

Don’t forget to add the commons-io dependency in the pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.wordpress.ykyuen</groupId>
	<artifactId>string-inputstream-conversions</artifactId>
	<version>1.0</version>
	
	<dependencies>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
	</dependencies>
</project>

 

Done =)

Reference:

2 thoughts on “Java – Convert String to InputStream”

  1. Hello

    I dont know JAVA language. But any one know how to develop mobile application in java.
    There are many sites which provide java based application for mobile. They are made in java with .jar extension.

    Also is it possible to retrieve all & recently received SMS from mobile inbox & send it to other mobile???

    I want to develop such type of application. So is it possible or not?

    Thanks & Reply

    Like

Leave a reply to ykyuen Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.