问题
I am using JRuby with a Java library. The type of an input parameter of the Java method is InputStream, and I am using JRuby to call this method, how could I revert something like "/directory/item.txt" to InputStream for the Java method? Thank you.
回答1:
Use RubyString#to_java_bytes
to convert the string to bytes, then wrap it in a java.io.ByteArrayInputStream,
which is a subclass of java.io.InputStream
:
>> "an arbitrary string"
"an arbitrary string"
>> _.to_java_bytes
=> byte[97, 110, 32, 97, 114, 98, 105, 116, 114, 97, 114, 121, 32, 115, 116, 114, 105, 110, 103]@7133da86
>> java.io.ByteArrayInputStream.new(_)
=> #<Java::JavaIo::ByteArrayInputStream:0x73e22a3d>
>> _.java_kind_of? java.io.InputStream
=> true
All at once:
inputstream = java.io.ByteArrayInputStream.new("an arbitrary string".to_java_bytes)
来源:https://stackoverflow.com/questions/45048528/how-to-convert-org-jruby-rubystring-to-java-io-inputstream