OutputStreamWriter转OutputStream
时间: 2023-06-14 16:04:27 浏览: 52
要将一个 `OutputStreamWriter` 转换成 `OutputStream`,可以使用 `OutputStreamWriter` 的 `getOutputStream()` 方法。例如:
```
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8");
OutputStream outputStream = writer.getOutputStream();
```
这样就可以得到一个 `OutputStream` 对象,可以用来写入数据。注意,转换为 `OutputStream` 后,就不能再使用 `write()` 方法来写入字符串了,而应该使用 `write(byte[] b)` 或 `write(byte[] b, int off, int len)` 方法。
相关问题
jdk17 OutputStreamWriter 转 OutputStream
在JDK 17中,可以使用OutputStreamWriter将字符流转换为字节流。下面是一个示例代码,演示如何使用OutputStreamWriter将字符串写入到OutputStream中:
```java
String str = "Hello, world!";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (OutputStreamWriter osw = new OutputStreamWriter(baos, StandardCharsets.UTF_8)) {
osw.write(str);
}
byte[] bytes = baos.toByteArray();
```
在上面的代码中,我们首先创建了一个字符串"Hello, world!",然后创建了一个ByteArrayOutputStream对象baos。接着,我们使用OutputStreamWriter将字符串写入到baos中,并指定了字符编码为UTF-8。最后,我们将baos转换为字节数组bytes。
OutputStreamWriter获取OutputStream
要获取`OutputStreamWriter`的`OutputStream`,可以使用`getOutputStream()`方法。例如:
```
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("example.txt"));
OutputStream outputStream = writer.getOutputStream();
```
这将创建一个`OutputStreamWriter`对象,该对象将文本数据写入到名为"example.txt"的文件中。然后,`getOutputStream()`方法将返回与该`OutputStreamWriter`对象关联的`OutputStream`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)