How to read a Binary Document from Couchbase - JavaSDK 2 API


#1

I am trying to insert and retrieve small files in couchbase, insertion is successful but when I try to fetch the content and write it to a file am getting below error.

I wish not to encode into base64 as these are small jpeg/video/audio files (< 1MB)

BinaryDocument responsefromDB = bucket.get(“KESAVAN”, BinaryDocument.class);
try {
FileOutputStream ostream = new FileOutputStream(“C:\Satz\Test - Copy\Output.txt”);
ostream.write(responsefromDB.content().array());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Error:
Error : Exception in thread “main” java.lang.UnsupportedOperationException: direct buffer at com.couchbase.client.deps.io.netty.buffer.PooledUnsafeDirectByteBuf.array(PooledUnsafeDirectByteBuf.java:363) at com.couchbase.client.deps.io.netty.buffer.SlicedByteBuf.array(SlicedByteBuf.java:97) at com.couchbase.client.deps.io.netty.buffer.CompositeByteBuf.array(CompositeByteBuf.java:463) at com.util.task.CouchbaseClient.main(CouchbaseClient.java:52)


#2

Seems like this is happening during:

Can you show us how you have written the Document in the first place? Did you use a BinaryDocument?


#3

Yes, I used a Binary Document

	FileInputStream fileInputStream=null;
	File file = new File("C:\\Satz\\Test - Copy\\testingnewcopu.txt");
	byte[] bFile = new byte[(int) file.length()];
    try {
        //convert file into array of bytes
	    fileInputStream = new FileInputStream(file);
	    fileInputStream.read(bFile);
	    fileInputStream.close(); 
    System.out.println("Done");
    }catch(Exception e){
    	e.printStackTrace();
    }
		    
	ByteBuf bytebuf = Unpooled.copiedBuffer(bFile);
	BinaryDocument bdoc = BinaryDocument.create("KESAVAN", bytebuf);
	BinaryDocument response = bucket.upsert(bdoc);

#4

@coolksathiya the ByteBuf from netty is direct, so it is not backed by an array. The most efficient way to extract out the bytes into a byte array is the following:

byte[] data = new byte[content.readableBytes()];
content.readBytes(data);

Note that of course this does a memory copy, but sometime it is needed if an API expects a byte[]. If not, you can use many of the methods on the ByteBuf to manipulate or iterate.