java 如何用 StringReader 替换 StringBufferInputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2219439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace StringBufferInputStream with StringReader?
提问by Frank
Using JNLP, I have this line :
使用 JNLP,我有这一行:
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 ?
如何在这一行中用 StringReader 替换 StringBufferInputStream ?StringBufferInputStream 的 API 说最好使用 StringReader,但是如何在不同类型之间进行转换?
回答by Thilo
FileSaveService.saveFileDialog takes an InputStream, not a Reader (because it wants binary data, not character data).
FileSaveService.saveFileDialog 需要一个 InputStream,而不是一个 Reader(因为它需要二进制数据,而不是字符数据)。
StringBufferInputStream is deprecated because it does not convert characters into bytes properly.
StringBufferInputStream 已被弃用,因为它没有正确地将字符转换为字节。
You can use ByteArrayInputStream instead:
您可以使用 ByteArrayInputStream 代替:
new ByteArrayInputStream("the string".getBytes("UTF-8"))
回答by Stephen C
The standard Java class libraries offer no way to wrap a Readeras an InputStream, but the following SO question and its answers offer some solutions. Be careful to read the fine-print!
标准 Java 类库无法将 a 包装Reader为 an InputStream,但以下 SO 问题及其答案提供了一些解决方案。仔细阅读细则!
How to convert a Reader to InputStream and a Writer to OutputStream?
如何将 Reader 转换为 InputStream,将 Writer 转换为 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 StringInputStreamwith a ByteArrayInputStreamas described by @Thilo's answer.
但是,坚持使用您所拥有的内容(如果这只是单元测试代码......看起来如此)或者StringInputStream用ByteArrayInputStream@Thilo 的答案所描述的a替换更简单。

