当我使用NIO2通道读取此字符串时:
È bla bla bla我在我的控制台中得到了这个:
? bla bla bla我想知道如何设置字符集,当代码是这样的时候:
RandomAccessFile aFile = new RandomAccessFile("in.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();我想设置如下内容:
StandardCharsets.ISO_8859_1发布于 2013-07-28 20:31:22
正如您从代码中看到的,您正在从FileChannel读取字节。您将如何解释这些字节取决于您。
在您的代码中,当您执行System.out.print((char) buf.get());操作时,读取的字节将被转换为字符串。这就是您看到该输出的原因。
尝试使用contructor that specifies the desired character set显式创建新的String,即String(byte[] bytes, Charset charset)
https://stackoverflow.com/questions/17908096
复制相似问题