kostaskougios / cloning

deep clone java objects
Other
591 stars 111 forks source link

Deep copy of a BufferedInputStream #51

Open pacellig opened 8 years ago

pacellig commented 8 years ago

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.

kostaskougios commented 8 years ago

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).

pacellig commented 8 years ago

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

kostaskougios commented 8 years ago

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.

LitnhJacuzzi commented 3 years ago

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.