1616import javax .annotation .Nullable ;
1717
1818public class DownloadUtils {
19- private static void download (URL url , OutputStream os , String fileName ) throws IOException {
19+ private static void download (URL url , OutputStream os , long size ) throws IOException {
2020 final int MAX_RETRIES = 3 ;
2121 int attempts = 0 ;
2222
@@ -29,8 +29,11 @@ private static void download(URL url, OutputStream os, String fileName) throws I
2929 conn .connect ();
3030
3131 if (conn .getResponseCode () == HttpURLConnection .HTTP_OK ) {
32- int totalBytes = conn .getContentLength (); // Get the total size of the file
33- try (InputStream is = new StreamDL (conn .getInputStream (), totalBytes )) {
32+ if (size == -1 ) {
33+ size = conn .getContentLengthLong ();
34+ }
35+
36+ try (InputStream is = new StreamDL (conn .getInputStream (), size )) {
3437 IOUtils .copy (is , os );
3538 }
3639 return ;
@@ -44,11 +47,15 @@ private static void download(URL url, OutputStream os, String fileName) throws I
4447 }
4548
4649 public static void downloadFile (String url , File out ) throws IOException {
50+ downloadFile (url , out , -1 );
51+ }
52+
53+ public static void downloadFile (String url , File out , long size ) throws IOException {
4754 Objects .requireNonNull (out .getParentFile ()).mkdirs ();
4855 File tempOut = File .createTempFile (out .getName (), ".part" , out .getParentFile ());
4956 try {
5057 try (OutputStream bos2 = new BufferedOutputStream (Files .newOutputStream (tempOut .toPath ()))) {
51- download (new URL (url ), bos2 , out . getName () );
58+ download (new URL (url ), bos2 , size );
5259 tempOut .renameTo (out );
5360 bos2 .close ();
5461 if (tempOut .exists ()) tempOut .delete ();
0 commit comments