kolrie
kolrie

Reputation: 12732

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?

Upvotes: 6

Views: 2266

Answers (3)

user3391413
user3391413

Reputation: 1

For me

f = java.lang.Object.new
stream = f.java_class.resource_as_stream('/myfile.txt') returned nil.

Following way worked fine from ruby

stream = self.to_java.get_class.get_class_loader.get_resource_as_stream('myfile.txt')

Upvotes: 0

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()

Upvotes: 5

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

In Java, you read files out of a jar using, for example, Class.getResourceAsStream(). I don't know JRuby, but I suspect that that's what you're going to have to do, fall back to Java (however that works) and get the InputStream from one of the getResource() calls. A jar entry is not accessible as a File in Java, so I wouldn't expect it to be so accessible in JRuby, either.

Upvotes: 1

Related Questions