开发者

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开发者_C百科.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?


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


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.


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜