Convert String to Reader in Java

May 16, 2020 No comments Java IO Conversions String Reader

1. Introduction

In this article, we are going to present various ways to convert String to Reader in Java. We will use plain Java solution and external libraries such as Guava and Apache Commons IO. String to Reader conversion is pretty natural, because Readers are character-based streams.

If you are looking for more Java I/O articles, check the following links:

2. Convert String to Reader using plain Java

Let's take a look at a pure Java solution:

package com.frontbackend.java.io.conversions.toreader.fromstring;

import java.io.Reader;
import java.io.StringReader;

public class StringToReaderUsingPlainJava {

    public static void main(String[] args) {
        String str = "frontbackend.com";
        Reader reader = new StringReader(str);
    }
}

As you can see plain Java provides a simple one-line solution to this kind of conversions. In this example, we used StringReader which extends the Reader class and provides all the necessary methods.

3. String to Reader with Guava

To convert String to Reader we can also use Guava library, that provides many utility classes for I/O operations:

package com.frontbackend.java.io.conversions.toreader.fromstring;

import java.io.IOException;
import java.io.Reader;

import com.google.common.io.CharSource;

public class StringToReaderUsingGuava {

    public static void main(String[] args) throws IOException {
        String str = "frontbackend.com";
        Reader reader = CharSource.wrap(str)
                                  .openStream();
    }
}

In this example, we used CharSource class that wraps given String and create character-based stream out of it.

4. String to Reader using Apache Commons IO library

The Apache Commons IO library also comes with a straightforward solution for this kind of conversion:

package com.frontbackend.java.io.conversions.toreader.fromstring;

import java.io.Reader;

import org.apache.commons.io.input.CharSequenceReader;

public class StringToReaderUsingApacheCommonsIO {

    public static void main(String[] args) {
        String str = "frontbackend.com";
        Reader reader = new CharSequenceReader(str);
    }
}

This example used CharSequenceReader class (that extends an abstract Reader class) that wraps given String.

5. Conclusion

In this article, we presented three ways to convert String to Reader using plain Java, Guava, and Apache Commons IO library. These three solutions are simple and straightforward.

All examples used in this tutorial are available under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}