64

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?

1
  • String Reader is working fine. I have used filereader instead of writing my own method this is simpler. (Reader)new FileReader(filePath); Commented Dec 19, 2011 at 8:01

4 Answers 4

119

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I'd add that if you're using Eclipse, pulling up a tree of all known subclasses for any type is as easy as hitting F4 when the cursor is on the type (e.g. Reader). I presume other IDEs are similarly equipped. Tremendously helpful in these situations.
This answers the literal question in the title and is probably why 90% came here. But @JonLin's answer has a better solution for the specific situation described by OP.
11

Or you can simply create a FileReader and return that.

1 Comment

He says he has a method that reads a file and he wants to return a Reader instead of a String
10

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);

1 Comment

"jumpS", not "jumpED", otherwise not all 26 characters are used ;-).
0

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.