Author: msahyoun
Date: Thu Apr  9 17:52:53 2026
New Revision: 1932931

Log:
PDFBOX-5660: close RandomAccessOutputStream in case of failure

Modified:
   pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/cos/COSStream.java

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/cos/COSStream.java
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/cos/COSStream.java      
Thu Apr  9 17:26:30 2026        (r1932930)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/cos/COSStream.java      
Thu Apr  9 17:52:53 2026        (r1932931)
@@ -231,25 +231,40 @@ public class COSStream extends COSDictio
         else
             randomAccess = getStreamCache().createBuffer();
         OutputStream randomOut = new RandomAccessOutputStream(randomAccess);
-        OutputStream cosOut = new COSOutputStream(getFilterList(), this, 
randomOut,
-                getStreamCache());
-        isWriting = true;
-        return new FilterOutputStream(cosOut)
+        boolean success = false;
+
+        try
         {
-            @Override
-            public void write(byte[] b, int off, int len) throws IOException
+            OutputStream cosOut = new COSOutputStream(getFilterList(), this, 
randomOut,
+                    getStreamCache());
+            isWriting = true;
+            FilterOutputStream result = new FilterOutputStream(cosOut)
             {
-                this.out.write(b, off, len);
-            }
-            
-            @Override
-            public void close() throws IOException
+                @Override
+                public void write(byte[] b, int off, int len) throws 
IOException
+                {
+                    this.out.write(b, off, len);
+                }
+                
+                @Override
+                public void close() throws IOException
+                {
+                    super.close();
+                    setInt(COSName.LENGTH, (int)randomAccess.length());
+                    isWriting = false;
+                }
+            };
+            success = true;
+            return result;
+        }
+        finally
+        {
+            if (!success)
             {
-                super.close();
-                setInt(COSName.LENGTH, (int)randomAccess.length());
-                isWriting = false;
+                // clean up partially written data
+                randomOut.close();
             }
-        };
+        }
     }
     
     /**

Reply via email to