java - ReadableBytechannel.read 始终返回 -1

标签 java io nio

我正在使用 ReadableByteChannel 来读取文件。

代码片段如下

   InputStream in = new FileInputStream("Copy.tiff");
   FileInputStream in1 = new FileInputStream("Copy.tiff");
   FileChannel inChannel = in1.getChannel();
   ReadableByteChannel srcChannel = null;
   srcChannel = Channels.newChannel(in);
   ByteBuffer buffer = ByteBuffer.allocate(1024);
   long pos1 = 0;
   buffer.rewind();
   pos1= srcChannel.read(buffer);//Here value is -1
   pos1 = inChannel.read(buffer);//Here some positive number

如果我使用InputStream读取方法总是返回-1。 如果我使用 FileInputStream 它会返回一个正数。 谷歌搜索没有提供任何合适的答案。 有关出现问题的任何反馈。

最佳答案

我无法重现此内容(在 Windows 上)。我通过这两种方法都获得了正值,并且我不明白为什么它会失败。也许这是一些可怕的依赖于实现的怪癖。

FileChannel(由 FileInputStream.getChannel() 返回)已经实现了 ReadableByteChannel,所以我想知道为什么您要手动创建一个?

关于java - ReadableBytechannel.read 始终返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7687913/

相关文章:

java - 可以通过更改系统日期来绕过检查到期日期

linux - 在 Linux 中读取没有磁盘缓存的文件

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

c - 使用 fopen() 读取文件无法正常工作

Java和视频播放器

java - 使用 XSAttributeUse.getValueConstraintValue() 时,Apache Xerces 抛出 java.lang.NoSuchMethodError

Eclipse 中的 Java 错误 : Could not find or load main class length

java - 使用java输入输出

Windows 系统上的 java7 : Files. walkFileTree() 和 "System Volume information"

java - 为什么我们需要 Java NIO 选择器?