java.nio.channels在输出中的字符之间显示哪些空格
代码: 输出如下所示: G a r b a G e in,G a r b a G e u t。G a r b a G e in,G a r b a G e u t。 这本书是:因为文件内容显示为8位字符 您正在向文件中写入Unicode字符,其中原始文件中的每个字符都会写入2个字节 一串 如何避免输出中字符之间出现空格java.nio.channels在输出中的字符之间显示哪些空格,java,io,channel,Java,Io,Channel,代码: 输出如下所示: G a r b a G e in,G a r b a G e u t。G a r b a G e in,G a r b a G e u t。 这本书是:因为文件内容显示为8位字符 您正在向文件中写入Unicode字符,其中原始文件中的每个字符都会写入2个字节 一串 如何避免输出中字符之间出现空格 英语不是我的母语。所以我可能描述得不好。谢谢 最简单的解决方案是使用字节而不是字符 String phrase = "Garbage in, garbage out.\n"; P
英语不是我的母语。所以我可能描述得不好。谢谢 最简单的解决方案是使用字节而不是字符
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();
}
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"));