📌  相关文章
📜  Java中将字节数组转换为Writer的程序(1)

📅  最后修改于: 2023-12-03 15:16:19.669000             🧑  作者: Mango

Java中将字节数组转换为Writer的程序

在Java中,可以使用ByteArrayInputStream将字节数组转换为输入流,然后使用InputStreamReader将输入流转换为Reader,最后可以将Reader转换为Writer。

以下是一个示例代码片段,演示如何将字节数组转换为Writer:


import java.io.*;

public class ByteArrayToWriterExample {
    public static void main(String[] args) throws IOException {
        byte[] bytes = "Hello, World!".getBytes();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        Writer writer = new StringWriter();
        char[] charBuffer = new char[2048];
        int bytesRead;
        while ((bytesRead = inputStreamReader.read(charBuffer)) != -1) {
            writer.write(charBuffer, 0, bytesRead);
        }
        String result = writer.toString();
        System.out.println(result);
    }
}

此代码将“Hello,World!”字符串转换为字节数组,创建ByteArrayInputStream对象并将其传递给InputStreamReader对象。然后,创建StringWriter对象并使用inputStreamReader将字节数组读取到char数组中,最后将char数组写入字符串中,返回打印输出的字符串。

以上是一个简单的示例,但这种方式可以在处理字节数组时非常有用。