File Reader example in JRuby
In this section of JRuby tutorial we will study to Read File in JRuby. We can read and write file on the console or in a file with the JRuby. Here in our example we are reading a text file and printing its content on the console.
FileReaderExample will take the input from the text file JRubyFile.txt and then by reading it line by line, print its content on your console as output. Here is the JRubyFile.txt as follows:
JRubyFile.txt
Hello ! Welcome to RoseIndia Technologies. 1. Amit Kumar Raghuwanshi 2. Vineet Bansal 3. Sandeep Suman 4. Vinod Kumar |
FileReaderExample.rb
require "java" include_class "java.io.BufferedReader" include_class "java.io.FileReader" fileReader = FileReader.new "JRubyFile.txt" bufferReader = BufferedReader.new fileReader str = bufferReader.readLine while str puts str.to_s str = bufferReader.readLine end |
In the above example code of FileReaderExample,
first line require "java" shows that we are making our JRuby
program enable to use java classes.
include_class "java.io.BufferedReader" include_class "java.io.FileReader" |
Above lines of code will include java classes FileReader
and BufferedReader in our program. It's like importing class in Java
program.
fileReader = FileReader.new "JRubyFile.txt" will create a new instance of
class FileReader with taking JRubyFile.txt as its argument.
To read line we have used BufferedReader's method readLine.
bufferReader = BufferedReader.new fileReader str = bufferReader.readLine while str puts str.to_s str = bufferReader.readLine end |
Above lines of code will create an instance of BufferedReader class and then we have to read first line of text file with the readLine method. For reading whole text file we have used while-loop in our program.
Here is the output of the FileReaderExample as generated on your screen:
Output:
C:\JRuby>jruby FileReaderExample.rb Hello ! Welcome to RoseIndia Technologies. 1. Amit Kumar Raghuwanshi 2. Vineet Bansal 3. Sandeep Suman 4. Vinod Kumar |