Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file within a Jar with JRuby

I am working on a Java wrapper for a library I created in JRuby and I can't manage to read a file that is within the JAR.

I have opened the JAR already and the file is there, located on the root folder of the JAR.

However, when I try to run:

File.read("myfile.txt")

It throws the following error:

C:\temp>java -jar c:\libraries\XmlCompare.jar
file:/C:/libraries/XmlCompare.jar!/lib/xmlcompare/app.rb:19:in `initialize': 
No such file or directory - myfile.txt (Errno::ENOENT)

I have even tried to make the path absolute (given that the text file is at the root and the ruby source that is executing is inside lib/xmlcompare), by doing:

File.read("#{File.dirname(__FILE__)}/../../myfile.txt")

But then I get:

C:\temp>java -jar c:\libraries\XmlCompare.jar
file:/C:/libraries/XmlCompare.jar!/lib/xmlcompare/app.rb:19:in `initialize': 
No such file or directory -
file:/C:/libraries/XmlCompare.jar!/lib/xmlcompare/../../myfile.txt 
(Errno::ENOENT)

Any idea on how I can make this work?

like image 653
kolrie Avatar asked Mar 31 '11 02:03

kolrie


1 Answers

As Ernest pointed out, this can be done in JRuby the Java way:

require 'java'
require 'XmlCompare.jar'

f = java.lang.Object.new
stream = f.java_class.resource_as_stream('/myfile.txt')
br = java.io.BufferedReader.new(java.io.InputStreamReader.new(stream))
while (line = br.read_line())
  puts line
end
br.close()
like image 181
Sébastien Le Callonnec Avatar answered Oct 23 '22 04:10

Sébastien Le Callonnec