开发者

Use Ruby to copy files into an jar file

开发者 https://www.devze.com 2023-04-13 06:58 出处:网络
my problem is that I want to add some .class files from a normal directory into an .jar file. Do I have to extract it before or can I add开发者_如何转开发 the files \"on the fly\"?Although I agree wit

my problem is that I want to add some .class files from a normal directory into an .jar file. Do I have to extract it before or can I add开发者_如何转开发 the files "on the fly"?


Although I agree with Jordan and suggest using the system command, that was not an option for the team I work on.

If you have to use his second solution, it is extremely important to note that Zip::ZipOutputStream will override any existing jars; i.e., you won't be adding to an existing jar, you will be creating a new one. This code will add a file to an existing jar:

require 'zip/zip'

Zip::ZipFile::open 'path/to/jar' do |jar|
  jar.add 'filename_in_jar', 'path/to/file/you/want/to/add'
end


If it was me I would almost certainly just call the jar command within Ruby to do this:

system 'jar uf jar_file.jar input_file(s).class'
# or
%x[ 'jar uf jar_file.jar input_file(s).class' ]

Reference here.

If you still want to do this without calling jar you should be able to do it with rubyzip, since JAR files are just ZIP files with a particular structure. Something like this:

require 'zip/zip'

filename = 'class_file.class'

Zip::ZipOutputStream::open "jar_file.jar" do |zip|
  zip.put_next_entry 'dest/path/in/jar/' + filename  # don't forget the path

  File.open filename, 'rb' {|f| zip.write f.read }
end

There are also a few Ruby wrappers for libarchive that could do this. E.g.

0

精彩评论

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

关注公众号