|
| 1 | +package net.hypercubemc.iris_installer; |
| 2 | + |
| 3 | +import java.io.BufferedOutputStream; |
| 4 | +import java.io.File; |
| 5 | +import java.net.URL; |
| 6 | +import javax.net.ssl.HttpsURLConnection; |
| 7 | +import javax.swing.SwingWorker; |
| 8 | + |
| 9 | +/* |
| 10 | + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license |
| 11 | + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template |
| 12 | + */ |
| 13 | +/** |
| 14 | + * |
| 15 | + * @author ims |
| 16 | + */ |
| 17 | +public class Downloader extends SwingWorker<Void, Void> { |
| 18 | + |
| 19 | + private final String url; |
| 20 | + private final File file; |
| 21 | + |
| 22 | + public Downloader(String url, File file) { |
| 23 | + this.url = url; |
| 24 | + this.file = file; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + protected Void doInBackground() throws Exception { |
| 29 | + URL url = new URL(this.url); |
| 30 | + HttpsURLConnection connection = (HttpsURLConnection) url |
| 31 | + .openConnection(); |
| 32 | + long filesize = connection.getContentLengthLong(); |
| 33 | + |
| 34 | + if (filesize == -1) { |
| 35 | + throw new Exception("Content length must not be -1 (unknown)!"); |
| 36 | + } |
| 37 | + |
| 38 | + long totalDataRead = 0; |
| 39 | + |
| 40 | + try ( java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream())) { |
| 41 | + java.io.FileOutputStream fos = new java.io.FileOutputStream(file); |
| 42 | + try ( java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024)) { |
| 43 | + byte[] data = new byte[1024]; |
| 44 | + int i; |
| 45 | + |
| 46 | + while ((i = in.read(data, 0, 1024)) >= 0) { |
| 47 | + totalDataRead = totalDataRead + i; |
| 48 | + bout.write(data, 0, i); |
| 49 | + |
| 50 | + int percent = (int) ((totalDataRead * 100) / filesize); |
| 51 | + |
| 52 | + setProgress(percent); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return null; |
| 57 | + } |
| 58 | +} |
0 commit comments