java.nio.channels 输出的字符之间显示什么空格

What display spaces between the characters in the output by java.nio.channels

代码:

String phrase = "Garbage in, garbage out.\n";
Path file = Paths.get(System.getProperty("user.home")).
        resolve("Beginning Java Stuff").resolve("charData.txt");
try {
    Files.createDirectories(file.getParent());
} catch (IOException e) {
    e.printStackTrace();
    System.exit(1);
}

try(WritableByteChannel channel = 
        Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))){
    ByteBuffer buf = ByteBuffer.allocate(1024);
    for(char ch : phrase.toCharArray())
        buf.putChar(ch);

    buf.flip();             
    channel.write(buf);         
    buf.flip();
    channel.write(buf);     
    buf.clear();
}catch(IOException e){
    e.printStackTrace();
}

输出如下: 垃圾进垃圾出 。垃圾进垃圾出 。 书上是:因为文件内容显示为8位字符 并且您正在将 Unicode 字符写入文件,其中为原始文件中的每个字符写入 2 个字节 细绳。 如何在输出中的字符之间不留空格;

英语不是我妈tongue.So我可能描述的不是well.Thanks!

最简单的解决方案是使用字节而不是字符。

final ByteBuffer buf = ByteBuffer.allocate(1024);
for (final byte ch : phrase.getBytes("UTF-8")) {
    buf.put(ch);
}
// or just
buf.put( phrase.getBytes("UTF-8"));