How to convert String to Reader in java

JavaFile Io

Java Problem Overview


I have a method which reads a file and returns a string, but I wanted to return a reader. I want to convert the string to a reader, or I want to read the file and return the reader. How can I do this?

Java Solutions


Solution 1 - Java

Use java.io.StringReader: return new StringReader(string);.

Next time you need a reader, you can check the "Direct known subclasses" of the Reader class. Same goes for InputStream, etc. The place to start is the javadoc - it contains quite a lot of useful information.

But for your task at hand, you'd better follow Jon Lin' advice of simply using a FileReader. There is no need to go through String. (For that, my advice from the previous paragraph applies as well)

Solution 2 - Java

Or you can simply create a FileReader and return that.

Solution 3 - Java

You can use StringReader class from java.io package.

String stringToBeParsed = "The quick brown fox jumped over the lazy dog";
StringReader reader = new StringReader(stringToBeParsed);

Solution 4 - Java

Try this sample code,

FileInputStream in = null;
    StringBuilder sb = new StringBuilder();
    String tempString = null;
    Reader initialReader;
    try {
        in = new FileInputStream(filename);
        initialReader = new InputStreamReader(in);

        char[] arr = new char[8 * 1024];
        StringBuilder buffer = new StringBuilder();
        int numCharsRead;
        while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
            buffer.append(arr, 0, numCharsRead);
        }
        String targetString = buffer.toString();
      
        result = IOUtils.toByteArray(targetString);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArasuView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaJon LinView Answer on Stackoverflow
Solution 3 - JavaAravind YarramView Answer on Stackoverflow
Solution 4 - JavaozanurkanView Answer on Stackoverflow