Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Tutorials Jruby File Reader example in JRuby

Related Tutorials


 
 

Share on Google+Share on Google+

File Reader example in JRuby

Advertisement
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.

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

Download Source Code

     

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 29, 2008

Related Tutorials

Discuss: File Reader example in JRuby  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com