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 ?

2 Answers 2

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"))
Sign up to request clarification or add additional context in comments.

3 Comments

The key point is the InputStream needs to know how to encode your bytes.
Yes, you need to pick an encoding (UTF-8 in the example above).
In Kotlin, use toByteArray() instead of getBytes("UTF-8") stackoverflow.com/a/46701367/211292
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.