cloning icon indicating copy to clipboard operation
cloning copied to clipboard

Deep copy of a BufferedInputStream

Open pacellig opened this issue 9 years ago • 4 comments

I tried to use the library in this way

        Cloner cloner=new Cloner();
        BufferedInputStream clonedBis = cloner.deepClone(bis);
        //create a byte array
        byte[] clonedContents = new byte[1024];

        int clonedBytesRead=0;
        String clonedStrFileContents;

        while( (clonedBytesRead = clonedBis.read(clonedContents)) != -1){

but the cloned BufferedInputStream doesn't seem to contain any data ( the while loop doesn't execute, since clonedBis.read(clonedContents) is -1.

pacellig avatar Jul 13 '16 11:07 pacellig

BufferedInputStream uses your original stream to fetch data. If you used a FileInputStream, chances are that the cloned FileInputStream contains a cloned FileDescriptor but with the same FileDescriptor.fd. This must be the low level OS file handler. So the behaviour of it will be unexpected. Maybe you already read the file using your "bis" BufferedInputStream and the cloned returns -1 (since it is the same low level file).

kostaskougios avatar Jul 13 '16 20:07 kostaskougios

Yes, I did already read the file using 'bis'. There is no way to clone an already read BufferedInputStream?

pacellig avatar Jul 18 '16 06:07 pacellig

Cloner can't clone the native file handler.

Also cloning non-java pointers can lead to jvm crashes, so I would recommend avoiding it. I think in this case it is better to just re-open the file if you need to re-read it.

kostaskougios avatar Jul 18 '16 20:07 kostaskougios

The stream read operation is fundamentally based on the file handler which gets by the long field handle in class FileDescriptor. It means different streams have different file handlers(even if two streams point to the same file), so the handle field of every stream instance should be different.But clone operation will make two streams have the same file handler, it causes two streams share one read() operation, when one of the stream reaches the end, the other stream's reading operation will return -1.

LitnhJacuzzi avatar Aug 06 '21 13:08 LitnhJacuzzi