I want to know how can I show the download percentage with this code. If you know an easier method than what I use please post a message about it.
Here it is my code :
public class DownloadURL {
private static String URL;
private static String outputFile;
public static void setURL(String url){
URL = url;
}
public static void setOutputFileName(String name){
outputFile=name;
}
public static void resetURL(){
URL = null;
}
public static void resetOutputFileName(){
outputFile=null;
}
public static void downloadFromURL(){
URL website;
if (URL != null || outputFile != null) {
try {
website = new URL(URL);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(outputFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
} catch (Exception e) {
Main.consolePrinter("Error in args or invalid page", new Type());
resetOutputFileName();
resetURL();
}
}
}
}
EDIT : NEW CODE
Download the files and print the percentage in the console :D
Thanks guys for helping me !
I'm french btw
public class DownloadURL {
private static String URL;
private static String outputFile;
public static void setURL(String url){
URL = url;
}
public static void setOutputFileName(String name){
outputFile=name;
}
public static void resetURL(){
URL = null;
}
public static void resetOutputFileName(){
outputFile=null;
}
public static void downloadFromURL(){
if (URL != null || outputFile != null) {
try {
URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0;
try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream())) {
FileOutputStream fos = new FileOutputStream(outputFile);
try (java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024)) {
byte[] data = new byte[1024];
int i;
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
float Percent = (totalDataRead * 100) / filesize;
Main.consolePrinter("Downloading Percent : " + Percent + "%", new Type());
}
}
}
} catch (Exception e) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, e.getMessage(), "Error",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}else{
Main.consolePrinter("Empty args !", new Type());
}
}
}