I am sure this is an easy one; I just couldn't find the answer immediately from Google.
I know I could do this (right?):
text = "" File.open(path).each_line do |line| text += line end # Do something with text
But that seems a bit excessive, doesn't it? Or is that the way one would do it in Ruby?
The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.
readAllBytes() Example. This is the standard way to read the whole file as String in Java. Just make sure the file is small or medium-size and you have enough heap space to hold the text from a file into memory. If you don't have enough memory, the below code can throw java.
The file read() method can be used to read the whole text file and return as a single string. The read text can be stored into a variable which will be a string. Alternatively the file content can be read into the string variable by using the with statement which do not requires to close file explicitly.
IO.read() is what you're looking for.
File is a subclass of IO, so you may as well just use:
text = File.read(path)
Can't get more intuitive than that.
What about IO.read()
?
Edit: IO.read()
, as an added bonus, closes the file for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With