diff --git a/StatusAPI/src/main/java/net/viper/status/FileDownloader.java b/StatusAPI/src/main/java/net/viper/status/FileDownloader.java new file mode 100644 index 0000000..632a5c7 --- /dev/null +++ b/StatusAPI/src/main/java/net/viper/status/FileDownloader.java @@ -0,0 +1,59 @@ +package net.viper.status; + +import net.md_5.bungee.api.plugin.Plugin; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.util.function.Consumer; + +/** + * FileDownloader: Lädt Dateien asynchron herunter (CMILib Style). + */ +public class FileDownloader { + + private final Plugin plugin; + + public FileDownloader(Plugin plugin) { + this.plugin = plugin; + } + + /** + * Lädt eine Datei herunter. + * @param urlString Die Download URL + * @param destination Die Zieldatei + * @param onSuccess Callback, der im Hauptthread ausgeführt wird, wenn fertig. + */ + public void downloadFile(String urlString, File destination, Runnable onSuccess) { + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + BufferedInputStream bufferedInputStream = null; + FileOutputStream fileOutputStream = null; + try { + URL url = new URL(urlString); + bufferedInputStream = new BufferedInputStream(url.openStream()); + fileOutputStream = new FileOutputStream(destination); + byte[] buffer = new byte[1024]; + int count; + while ((count = bufferedInputStream.read(buffer, 0, 1024)) != -1) { + fileOutputStream.write(buffer, 0, count); + } + + // Schließen + fileOutputStream.close(); + bufferedInputStream.close(); + + // Callback im Main Thread + plugin.getProxy().getScheduler().schedule(plugin, onSuccess, 1, java.util.concurrent.TimeUnit.MILLISECONDS); + + } catch (Throwable e) { + plugin.getLogger().warning("Download fehlgeschlagen: " + e.getMessage()); + if (destination.exists()) destination.delete(); + } finally { + if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException ignored) {} + if (bufferedInputStream != null) try { bufferedInputStream.close(); } catch (IOException ignored) {} + } + }); + } +} \ No newline at end of file