1. 程式人生 > 實用技巧 >Output streams Convert to byte array

Output streams Convert to byte array

Imagine that we have a typing machine that accepts only one letter at a time for writing, but we want to write an array of words instead.

public class LetterPrinter {
    public void write(char letter) {
        //implementation
    }
}

To adapt an input to the LetterPrinter we need to write a converter from String[]

to char[] and pass letters one by one to LetterPrinter instance:

public void writeWords(String[] words) throws IOException {
    LetterPrinter printer = new LetterPrinter();

    char[] letters = convert(words); // converting method
    for (char letter : letters) {
       printer.write(letter);
    }
}

Implement the convert method that converts String[] to char[].

Hint: use CharArrayWriter.

Example:
Input: ["This", " ", "is", " ", "a", " ", "test"]
Output: ["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t"]

import java.io.CharArrayWriter;
import java.io.IOException;

class Converter {
    public static char[] convert(String[] words) throws IOException {
        final var charArrayWriter = new CharArrayWriter();
        for (String word : words
             ) {
            charArrayWriter.write(word);
        }
        return  charArrayWriter.toCharArray();
    }
}