Ruby学习十 JRuby中调用java代码

本文介绍使用JRuby调用Java方法及处理压缩文件的具体实现。通过实例展示了如何利用JRUBY加载Java类库并实现CSV文件读取,同时提供打包Java程序为JAR文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

require 'java'

 

# 以下请注意要用相对路径

require 'C:/jruby-1.6.2/lib/opencsv-2.2.jar'
require 'C:/jruby-1.6.2/lib/UncompressInputStream.jar'

 

class UnCompress
  def get_input_stream(file)
    input = java.io.FileInputStream.new(file);
    if /\.gz$/ =~ file
      input = java.util.zip.GZIPInputStream.new(input);
    elsif  /\.Z$/ =~ file
      input = Java::org.amanzi.uncompress.UncompressInputStream.new(input);
    end
    input
  end

  def un_compress_file(file)
    p "start."
    input_stream = get_input_stream(file)
    character_set = java.lang.String.new("UTF-8")
    reader = Java::au.com.bytecode.opencsv.CSVReader.new(java.io.InputStreamReader.new(input_stream,character_set))
    all_line = []
    while (next_line = reader.readNext)
      all_line << next_line[0]
    end
    all_line
    p all_line
  end
end

 

2、调用java 方法时:

Java::包路径.方法名称

Java::com.dingli.test.TestJrubyCallJava()

 

3、java 打成 jar 包:

 

A. 先生成.class 文件.

B.源文件(.java) 需要带有包路径 eg:package com.dingli.test;

C.jar cvfm TestJrubyCallJava.jar mymanifest -C class/ .

 

D.class 的目录结构为:class/com/dingli/test/TestJrubyCallJava.class

 

这样打出来的jar 是带用包路径的。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值