【问题标题】:What display spaces between the characters in the output by java.nio.channelsjava.nio.channels 输出的字符之间显示什么空格
【发布时间】:2016-04-22 13:29:01
【问题描述】:

代码:

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 个字节 细绳。 如何在输出中的字符之间不留空格;

英语不是我的母语。所以我可能描述得不好。谢谢!

【问题讨论】:

    标签: java io channel


    【解决方案1】:

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

    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"));
    

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 1970-01-01
      • 2021-02-01
      • 2018-05-17
      • 1970-01-01
      • 2021-12-30
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多