简体   繁体   中英

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

code:

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();
}

the output like th following: G arbagein , garbageout . G arbagein , garbageout . The book is: Because the file contents are displayed as 8-bit characters and you are writing Unicode characters to the file where 2 bytes are written for each character in the original string. How to not spaces between the characters in the output;

English is not my mother tongue.So I maybe describe not well.Thanks!

The easiest solution will be to use bytes instead of characters.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM