42 lines
1.8 KiB
Java
42 lines
1.8 KiB
Java
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;
|
|
|
|
public class FileDownloader {
|
|
private final Plugin plugin;
|
|
|
|
public FileDownloader(Plugin plugin) { this.plugin = plugin; }
|
|
|
|
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);
|
|
}
|
|
fileOutputStream.close();
|
|
bufferedInputStream.close();
|
|
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) {}
|
|
}
|
|
});
|
|
}
|
|
} |