How to convert org.jruby.RubyString to java.io.InputStream

廉价感情. 提交于 2019-12-11 06:27:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!