Jruby:如何使用第三方java库?

Jruby: How to use third party java library?

我想使用java第三方二维码库https://github.com/kenglxn/QRGen二维码生成库

请指导我,因为我不知道如何在 jruby 中集成 java 库。

本例中的技巧是找到如何正确导入第 3 方库

  • 请使用任何依赖系统下载所需的 jar(我使用 ant 和 ivy)。
  • 这将根据您提到的二维码库下载5个jar:core-2.0.jar core-3.1.0.jar javase-2.0.jar javase-3.1.0.jar jfreesvg-2.1.jar

build.xml 蚂蚁:

<project xmlns:ivy="antlib:org.apache.ivy.ant" name="" default="retrieve">
  <!--setproxy proxyhost="" proxyport="" proxyuser="" proxypassword=""/-->
  <target name="retrieve">
    <ivy:retrieve/>
  </target>
</project>

ivy.xml 常春藤:

<ivy-module version="2.0" >
  <info organisation="" module=""/>
  <dependencies defaultconf="default">
    <dependency org="net.glxn.qrgen" name="javase" rev="2.0"/>
  </dependencies>
</ivy-module>

现在输入 ant retrieve 将下载 5 个 jar 并将其存储在 lib 子文件夹中。

如果您没有依赖管理器,这里是您需要手动下载的 5 个 jar url,您需要移动到名为 lib 的子文件夹:

强烈建议您使用java依赖管理器,如果您希望有朝一日升级java的修订版此代码片段中使用的库。

下一步是在同一文件夹中使用以下 ruby snip.rb 代码。 :

require 'java'
%w[
  lib/core-2.0.jar
  lib/core-3.1.0.jar
  lib/javase-2.0.jar
  lib/javase-3.1.0.jar
  lib/jfreesvg-2.1.jar
].map &method(:require)

# this is the CRITICAL line to get it to work...
include_class 'net.glxn.qrgen.javase.QRCode' 

# get QR file from text using defaults
# this will write a file (example: QRCode7247556396487679822.png) in java.io.tmpdir as defined in your JVM
file = QRCode.from("Hello World").file()
p file.name

# get QR stream from text using defaults
# if we redirect the stream as a byte array, we can have a better file control
include_class 'java.io.FileOutputStream'
stream = QRCode.from("Hello World").stream()
fos = FileOutputStream.new("QRCode.png")
fos.write(stream.toByteArray())
fos.close()

# fun with VCards
include_class 'net.glxn.qrgen.core.vcard.VCard' 
johnDoe = VCard.new("John Doe")
johnDoe.setEmail("john.doe@example.org")
johnDoe.setAddress("John Doe Street 1, 5678 Doestown")
johnDoe.setTitle("Mister")
johnDoe.setCompany("John Doe Inc.")
johnDoe.setPhoneNumber("1234")
johnDoe.setWebsite("www.example.org")
stream = QRCode.from(johnDoe).stream()
fos = FileOutputStream.new("VCard.png")
fos.write(stream.toByteArray())
fos.close()

# all generated PNG can be decoded online using http://zxing.org/w/decode.jspx

请注意: jruby 和 java.io.tmpdir 在这个特殊的 jar 案例中不能很好地协同工作,因为任何使用 [= 创建 QRcode 的调用16=] 将文件存储在 java.io.tmpdir 中,无论它位于何处。您几乎无法控制文件位置。

所以我修改了原始代码答案以改为使用流并创建具有更好控制的文件。

您可以验证用这个有用的 URL 生成的所有文件:http://zxing.org/w/decode.jspx