Java String to Inputstream

Java String to Inputstream

In this post, we will go through different options at how to convert  Java String to InputStream using Java and Apache Commons IO library

1. Convert Using Plain Java

Use ByteArrayInputStream to convert Java String to InputStream

 

public class StringToIOJava {

    public static void main(String[] args) throws IOException {

        String inputString = "This is a String to demo as how to convert it to input stream using Core Java API";

        //String to input stream
        try (InputStream inputStream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            String content;

            while ((content = bufferedReader.readLine()) != null) {
                //work with file
            }

        }
    }
}

 

 It’s always recommended to pass explicit Charset to the method getBytes() to avoid any unwanted behaviour.Java will pick platform’s default charset if not passed to the method.

 

1. Convert Using Apache Commons IO

Apache Commons IO provides short and concise solution for convert String to InputStream

 

public class StringToIOApache {

    public static void main(String[] args) throws IOException {

        String inputString = "This is a String to demo as how to convert it to input stream using Apache Commons IO";

        InputStream inputStream = IOUtils.toInputStream(inputString, StandardCharsets.UTF_8);

    }
}

In this post, we saw two easy and concise way to convert simple String to InputStream.

Please read Convert InputStream to String in Java to check how to Convert InputStream to String in Java.

 

All the code of this article is available Over on Github. This is a Maven-based project.

References

  1. ByteArrayInputStream
  2. Apache Commons IO

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

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

  Subscribe  
Notify of