Java 将字符串写入输出流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4069028/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:14:10  来源:igfitidea点击:

Write string to output stream

javastream

提问by yart

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.

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

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

现在,我收到了字符串。在这里写入流的最佳方式是什么?

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?

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

Do I need to use some bridge streams here instead?

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

采纳答案by MForster

Streams (InputStreamand OutputStream) transfer binarydata. If you want to write a string to a stream, you must first convert it to bytes, or in other words encodeit. 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.

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

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.

但是,将字符数据写入流的常用方法是将流包装在 a Writer, (通常是 a PrintWriter)中,当您调用它的write(String)(or print(String)) 方法时,它会为您进行转换。InputStreams 的相应包装器是Reader

PrintStreamis a special OutputStreamimplementation 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 PrintStreamor some other stream implementation. There is no danger of double encoding.

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

Example of PrintWriter with OutputStream:

带有 OutputStream 的 PrintWriter 示例:

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

回答by NG.

Wrap your OutputStream with a PrintWriterand use the print methods on that class. They take in a String and do the work for you.

PrintWriter包装您的 OutputStream并使用该类上的打印方法。他们接受一个字符串并为您完成工作。

回答by Illarion Kovalchuk

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

您可以创建一个环绕输出流的 PrintStream,然后将其称为 print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();

回答by Peter Knego

OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:

OutputStream 写入字节,String 提供字符。您需要定义 Charset 将字符串编码为 byte[]:

outputStream.write(string.getBytes(Charset.forName("UTF-8")));

Change UTF-8to a charset of your choice.

更改UTF-8为您选择的字符集。

回答by Antonio

By designit is to be done this way:

按照设计,它是这样完成的:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush

回答by Felix

You may use Apache Commons IO:

您可以使用Apache Commons IO

try (OutputStream outputStream = ...) {
    IOUtils.write("data", outputStream, "UTF-8");
}