Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to Reader in java

Tags:

java

file-io

People also ask

Can we convert string to file in java?

In this example, we shall use Apache's commons.io package to write string to file. Create file object with the path to the text file. Have your data ready in a string. Call the method FileUtils.


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)


Or you can simply create a FileReader and return that.


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