这里我有以下来自 this 的代码oracle java教程:
// Defaults to READ
try (SeekableByteChannel sbc = Files.newByteChannel(file)) {
ByteBuffer buf = ByteBuffer.allocate(10);
// Read the bytes with the proper encoding for this platform. If
// you skip this step, you might see something that looks like
// Chinese characters when you expect Latin-style characters.
String encoding = System.getProperty("file.encoding");
while (sbc.read(buf) > 0) {
buf.rewind();
System.out.print(Charset.forName(encoding).decode(buf));
buf.flip();//LINE X
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
所以基本上我没有得到任何输出。
我试图在 while 循环中放置一些标志来检查它是否进入,并且它进入。我还更改了 Charset.defaultCharset().decode(buf)
中的编码,结果:没有输出。
当然,文件中有文本传递给 newByteChannel(file);
有什么想法吗? 预先非常感谢。
**
编辑:
** 已解决,这只是我试图访问的文件之前被意外损坏的。更改文件后,一切正常。
最佳答案
代码看起来有问题。尝试将 rewind()
更改为 flip(),
,将 flip()
更改为 compact()。
关于java - Oracle 代码片段不返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466244/