简体   繁体   English

将字符串写入输出流

[英]Write string to output stream

I have several output listeners that are implementing OutputStream .我有几个正在实现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;它可以是写入标准输出或文件的PrintStream ,也可以是写入内存或任何其他输出目的地; therefore, I specified OutputStream as (an) argument in the method.因此,我在方法中将OutputStream指定为 (an) 参数。

Now, I have received the String .现在,我收到了String What is the best way to write to streams here?在这里写入流的最佳方式是什么?

Should I just use Writer.write(message.getBytes()) ?我应该只使用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 and OutputStream ) transfer binary data.流( InputStreamOutputStream )传输二进制数据。 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.您可以使用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.但是,将字符数据写入流的常用方法是将流包装在Writer (通常是PrintWriter )中,当您调用它的write(String) (或print(String) )方法时,它会为您进行转换. The corresponding wrapper for InputStreams is a Reader . InputStreams 的相应包装器是Reader

PrintStream is a special OutputStream implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). PrintStream是一种特殊的OutputStream实现,因为它还包含自动编码字符串的方法(它在内部使用编写器)。 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.无论是PrintStream还是其他一些流实现,您都可以安全地使用编写器包装您的流。 There is no danger of double encoding.没有双重编码的危险。

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();
}

OutputStream writes bytes, String provides chars. OutputStream 写入字节,String 提供字符。 You need to define Charset to encode string to byte[]:您需要定义 Charset 将字符串编码为 byte[]:

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

Change UTF-8 to a charset of your choice.UTF-8更改为您选择的字符集。

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 design it 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

Wrap your OutputStream with a PrintWriter and use the print methods on that class.PrintWriter包装您的 OutputStream 并使用该类上的打印方法。 They take in a String and do the work for you.他们接受一个字符串并为您完成工作。

You may use Apache Commons IO :您可以使用Apache Commons IO

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM