ReadableBytechannel.read always returns -1
I am using ReadableByteChannel to read from a file.
The code snippet is as below
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开发者_StackOverflow中文版 positive number
If I use InputStream read method always returns -1. If I use FileInputStream it returns a positive number. Googling did not provide any appropriate answer. Any feedback on what is going wrong.
I'm not able to reproduce this (on Windows). I get a positive value via both methods, and I don't see why it should fail. Maybe it's some awful implementation-dependent quirk.
FileChannel (as returned by FileInputStream.getChannel()) already implements ReadableByteChannel, so I wonder why you're creating one manually?
The following code works fine for me:
ByteBuffer buffer = ByteBuffer.allocate(1024);
InputStream in = new FileInputStream("Copy.tiff");
ReadableByteChannel srcChannel = Channels.newChannel(in);
long pos = srcChannel.read(buffer);
System.out.println("Position in channel: " + pos);
ReadableByteChannel srcChannel = new FileInputStream("Copy.tiff).getChannel();
精彩评论