net.chestmc.Downloader.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of chest-server Show documentation
Show all versions of chest-server Show documentation
A spigot fork to kotlin structure and news.
The newest version!
package net.chestmc
import net.chestmc.common.extensions.create
import net.chestmc.common.extensions.file
import net.chestmc.common.extensions.numbers.spaced
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
/**
* Represents a downloader used to download files from a URL.
*/
object Downloader {
/**
* Downloads the file at specified url and returns the file.
*/
fun download(url: URL, print: Boolean = false): File {
val connection = url.openConnection() as HttpURLConnection
val name = url.file.substring(url.file.lastIndexOf('/') + 1)
val file = kotlin.io.path.createTempFile(name).toFile()
if (print)
println("Downloading $name...")
connection.inputStream.buffered().use { input ->
file.outputStream().buffered().use { output ->
val copy = (input.copyTo(output) / 1024).spaced()
if (print)
println("Downloaded $name with $copy kb size")
}
}
return file
}
/**
* Downloads the file at specified url and implements inside of the specified folder
* and returns the file.
*/
fun download(url: URL, to: File, print: Boolean = false): File {
val name = url.file.substring(url.file.lastIndexOf('/') + 1)
val file = file(to, name)
if (file.exists()) return file else file.create()
val connection = url.openConnection() as HttpURLConnection
if (print)
println("Downloading $name...")
connection.inputStream.buffered().use { input ->
file.outputStream().buffered().use { output ->
val copy = (input.copyTo(output) / 1024).spaced()
if (print)
println("Downloaded $name with $copy kb size")
}
}
return file
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy