How to Write Strings to OutputStream in Java – 如何在 Java 中将字符串写入 OutputStream

最后修改: 2023年 12月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

We often work with OutputStream when we need to transfer data to external destinations such as files and networks. Data can either be in binary or string format. We use OutputStream, which is a byte stream, to deal with binary data, and Writer, which is a character stream, to deal with string data.

当我们需要将数据传输到外部目的地(如文件和网络)时,我们经常会使用 OutputStream 。数据可以是二进制格式,也可以是字符串格式。我们使用字节流 OutputStream 处理二进制数据,使用字符流 Writer 处理字符串数据。

However, there are situations where we have to write strings into an OutputStream due to the limitations imposed by the selected API. In some instances, the API may only provide OutputStream instead of Writer. In this tutorial, we’ll explore different methods for writing strings into OutputStream in such scenarios.

但是,在某些情况下,由于所选 API 的限制,我们必须将字符串写入 OutputStream 中。在某些情况下,API 可能只提供 OutputStream 而不是 Writer。在本教程中,我们将探讨在这种情况下将字符串写入 OutputStream 的不同方法。

2. Byte Conversion

2.字节转换

The most intuitive approach involves converting the string into bytes and then writing the converted bytes into the OutputStream:

最直观的方法是将字符串转换为字节,然后将转换后的字节写入OutputStream:

String str = "Hello";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
outputStream.write(bytes);

This approach is straightforward but has a major drawback. We need to explicitly convert the string into bytes beforehand and specify the character encoding each time when calling getBytes(). This makes our code cumbersome.

这种方法简单明了,但有一个很大的缺点。我们需要事先明确地将字符串转换为字节,并在每次调用 getBytes() 时指定 字符编码。这使我们的代码变得繁琐。

3. OutputStreamWriter

3.输出流写入器</em

A better approach is to utilize OutputStreamWriter to wrap our OutputStream. OutputStreamWriter serves as a wrapper that transforms a character stream into a byte stream. Strings written to it are encoded into bytes using the chosen character encoding.

一种更好的方法是利用 OutputStreamWriter 来封装我们的 OutputStream. OutputStreamWriter 作为封装器,可将字符流转换为字节流。写入其中的字符串将使用所选字符编码编码成字节。

We write the string via the write() method without specifying the character encoding. Each invocation of write() on OutputStreamWriter implicitly converts the string into encoded bytes, providing a more streamlined process:

我们通过 write() 方法写入字符串,而无需指定字符编码。每次在 OutputStreamWriter 上调用 write() 都会隐式地将字符串转换为编码字节,从而提供更精简的流程:

try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
    writer.write("Hello");
}

If the wrapped OutputStream is not yet buffered, we advise using the BufferedWriter to wrap around the OutputStreamWriter to make the writing process more efficient:

如果封装的 OutputStream 尚未缓冲,我们建议使用 BufferedWriter 来封装 OutputStreamWriter 以提高写入过程的效率:

BufferedWriter bufferedWriter = new BufferedWriter(writer);

This reduces IO operations by first writing data to a buffer and then flushing the buffered data to the stream in a larger chunk.

这样可以减少 IO 操作,首先将数据写入缓冲区,然后将缓冲区中的数据以较大的块刷新到数据流中。

4. PrintStream

4.打印流</em

Another option is to utilize PrintStream, which provides functionality similar to OutputStreamWriter. Similar to OutputStreamWriter, we can specify the encoding when we instantiate PrintStream:

另一种选择是使用 PrintStream, 它提供了与 OutputStreamWriter 类似的功能。OutputStreamWriter 类似,我们可以在实例化 PrintStream 时指定编码:

try (PrintStream printStream = new PrintStream(outputStream, true, StandardCharsets.UTF_8)) {
    printStream.print("Hello");
}

If we don’t define the character encoding explicitly in the constructor, the default encoding will be UTF-8:

如果我们没有在构造函数中明确定义字符编码,默认编码将是 UTF-8

PrintStream printStream = new PrintStream(outputStream);

The difference between PrintStream and OutputStreamWriter is that PrintStream provides additional print() methods for writing different data types to the OutputStream. Also, PrintWriter never throws an IOException for its print() and write() methods:

PrintStreamOutputStreamWriter 之间的区别在于,PrintStream 提供了额外的 print() 方法,用于将不同的数据类型写入 OutputStream 中。此外,PrintWriterprint()write() 方法永远不会抛出 IOException 异常:

printStream.print(100); // integer
printStream.print(true); // boolean

5. PrintWriter

5.打印写入器</em

PrintWriter serves a similar purpose to PrintStream, offering functionality for writing formatted representations of data to an OutputStream:

PrintWriter 的作用与PrintStream类似,提供将格式化的数据表示写入 OutputStream 的功能:</em

try (PrintWriter writer = new PrintWriter(outputStream)) {
    writer.print("Hello");
}

Besides wrapping OutputStream, PrintWriter provides additional constructors to wrap Writer as well. Another difference between them is that PrintWriter provides write() methods for writing character arrays, whereas PrintStream provides write() methods for writing byte arrays:

除了封装 OutputStream 之外,PrintWriter 还提供了额外的构造函数来封装 Writer 。它们之间的另一个区别是,PrintWriter 提供了用于写入字符数组的 write() 方法,而 PrintStream 提供了用于写入字节数组的 write() 方法:

char[] c = new char[] {'H', 'e', 'l' ,'l', 'o'};
try (PrintWriter writer = new PrintWriter(new StringWriter())) {
    writer.write(c);
}

6. Conclusion

6.结论

In this article, we’ve explored several approaches for writing strings to an OutputStream in Java.

在本文中,我们探讨了在 Java 中将字符串写入 OutputStream 的几种方法。

We began with the straightforward conversion of strings into bytes, which requires explicit encoding for each write operation and impacts the code’s maintainability. Subsequently, we explored three different Java classes that wrap around the OutputStream to encode strings into bytes seamlessly.

我们从直接将字符串转换为字节开始,这需要为每次写入操作进行显式编码,并影响代码的可维护性。随后,我们探索了三个不同的 Java 类,它们围绕 OutputStream 将字符串无缝地编码为字节。

As always, the sample code is available over on GitHub.

与往常一样,示例代码可在 GitHub 上获取。