【发布时间】: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 个字节 细绳。 如何在输出中的字符之间不留空格;
英语不是我的母语。所以我可能描述得不好。谢谢!
【问题讨论】: