How to replace StringBufferInputStream with StringReader?
Asked Answered
L

2

31

Using JNLP, I have this line :

File_Save_Service.saveFileDialog(null,null,new StringBufferInputStream("testing"),null);

How to replace StringBufferInputStream with StringReader in this line ? The API for StringBufferInputStream says better use StringReader, but how to convert between different types ?

Luxuriant answered 8/2, 2010 at 3:43 Comment(0)
G
47

FileSaveService.saveFileDialog takes an InputStream, not a Reader (because it wants binary data, not character data).

StringBufferInputStream is deprecated because it does not convert characters into bytes properly.

You can use ByteArrayInputStream instead:

new ByteArrayInputStream("the string".getBytes("UTF-8"))
Godmother answered 8/2, 2010 at 4:17 Comment(3)
The key point is the InputStream needs to know how to encode your bytes.Flair
Yes, you need to pick an encoding (UTF-8 in the example above).Godmother
In Kotlin, use toByteArray() instead of getBytes("UTF-8") https://mcmap.net/q/368371/-kotlin-equivalent-of-java-39-s-string-getbytesPtolemaeus
S
1

The standard Java class libraries offer no way to wrap a Reader as an InputStream, but the following SO question and its answers offer some solutions. Be careful to read the fine-print!

How to convert a Reader to InputStream and a Writer to OutputStream?

However, it is simpler to just stick with what you have got, (if this is just unit test code ... as it appears to be), or to replace the StringInputStream with a ByteArrayInputStream as described by @Thilo's answer.

Stivers answered 8/2, 2010 at 4:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.