Ravers Ravers - 22 days ago 11
Java Question

Convert a FileResource to a String

How can I convert a

FileResource
to a
String
?

Right now I have this:

FileResource resource = new FileResource("data/someText.txt");
String message = "";

for(String word : resource.words()) { message = message + word; }

System.out.println(message);


It is creating the message, but is not adding spaces or other chars.

How can I change the
resource.words()
to something that add's all the chars?

Answer

Use resource.lines() instead of words. OR asString() - Return entire contents of this opened file as one string.

http://www.dukelearntoprogram.com/course2/doc/javadoc/edu/duke/FileResource.html

FileResource resource = new FileResource("data/smallHamlet.txt");
StringBuilder message = new StringBuilder();

for(String line: resource.lines())
{
    str.append(line + " "); 
}
System.out.println(message);