将字符串写入输出流 [英] Write string to output stream

查看:525
本文介绍了将字符串写入输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个正在实现OutputStream的输出侦听器。
它可以是写入stdout或文件的PrintStream,也可以是写入内存或任何其他输出目的地;因此,我将OutputStream指定为方法中的(a)参数。

I have several output listeners that are implementing OutputStream. It can be either a PrintStream writing to stdout or to a File, or it can be writing to memory or any other output destination; therefore, I specified OutputStream as (an) argument in the method.

现在,我收到了String。在这里写入流的最佳方法是什么?

Now, I have received the String. What is the best way to write to streams here?

我应该只使用Writer.write(message.getBytes())吗?我可以给它字节,但如果目标流是字符流,那么它会自动转换吗?

Should I just use Writer.write(message.getBytes())? I can give it bytes, but if the destination stream is a character stream then will it convert automatically?

我是否需要在这里使用一些桥接流?

Do I need to use some bridge streams here instead?

推荐答案

Streams( InputStream OutputStream )传输二进制数据。如果要将字符串写入流,则必须先将其转换为字节,或者换句话说 encode 。你可以使用 String.getBytes(Charset)方法手动完成(如你所建议的那样),但你应该避免使用 String.getBytes()方法,因为它使用JVM的默认编码,无法以可移植的方式可靠地预测。

Streams (InputStream and OutputStream) transfer binary data. If you want to write a string to a stream, you must first convert it to bytes, or in other words encode it. You can do that manually (as you suggest) using the String.getBytes(Charset) method, but you should avoid the String.getBytes() method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.

通常的写法但是,流的字符数据是将流包装在 Writer ,(通常是 PrintWriter ),在您调用 write(String) (或 print(String) )方法。 InputStreams的相应包装器是 Reader

The usual way to write character data to a stream, though, is to wrap the stream in a Writer, (often a PrintWriter), that does the conversion for you when you call its write(String) (or print(String)) method. The corresponding wrapper for InputStreams is a Reader.

PrintStream 是一种特殊的 OutputStream 实现的意义它还包含自动编码字符串的方法(它在内部使用编写器)。但它仍然是一个流。无论是 PrintStream 还是其他一些流实现,您都可以安全地使用编写器包装流。没有双重编码的危险。

PrintStream is a special OutputStream implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a PrintStream or some other stream implementation. There is no danger of double encoding.

带有OutputStream的PrintWriter示例:

Example of PrintWriter with OutputStream:

try (PrintWriter p = new PrintWriter(new FileOutputStream("output-text.txt", true))) {
    p.println("Hello");
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
}

这篇关于将字符串写入输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆