@@ -46,6 +46,28 @@ static void writeStream(BoxAPIResponse response, OutputStream output, ProgressLi
4646 }
4747 }
4848
49+ /**
50+ * Writes response body bytes to output stream. After all closes the input stream.
51+ *
52+ * @param response Response that is going to be written.
53+ * @param output Output stream.
54+ * @param listener Listener that will be notified on writing response. Can be null.
55+ */
56+
57+ static void writeStreamWithContentLength (BoxAPIResponse response , OutputStream output , ProgressListener listener ) {
58+ try {
59+ InputStream input ;
60+ if (listener != null ) {
61+ input = response .getBody (listener );
62+ } else {
63+ input = response .getBody ();
64+ }
65+ writeStreamTo (input , output , response .getContentLength ());
66+ } finally {
67+ response .close ();
68+ }
69+ }
70+
4971 /**
5072 * Writes content of input stream to provided output. Method is NOT closing input stream.
5173 *
@@ -71,4 +93,31 @@ static void writeStreamTo(InputStream input, OutputStream output) {
7193 }
7294 }
7395 }
96+
97+ static void writeStreamTo (InputStream input , OutputStream output , long expectedLength ) {
98+ long totalBytesRead = 0 ;
99+ if (expectedLength < 0 ) {
100+ throw new RuntimeException ("No Data bytes in stream" );
101+ }
102+ try {
103+ byte [] buffer = new byte [8192 ];
104+ for (int n = input .read (buffer ); n != -1 ; n = input .read (buffer )) {
105+ output .write (buffer , 0 , n );
106+ totalBytesRead += n ; // Track the total bytes read
107+ }
108+ if (totalBytesRead != expectedLength ) {
109+ throw new IOException ("Stream ended prematurely. Expected " + expectedLength
110+ + " bytes, but read " + totalBytesRead + " bytes." );
111+ }
112+ } catch (IOException e ) {
113+ throw new RuntimeException ("Error during streaming: " + e .getMessage (), e );
114+ } finally {
115+ try {
116+ input .close ();
117+ output .close ();
118+ } catch (IOException closeException ) {
119+ throw new RuntimeException ("IOException during stream close" , closeException );
120+ }
121+ }
122+ }
74123}
0 commit comments