我想知道如何使用此代码显示下载百分比。 如果您比我使用的方法更简单,请发布有关它的消息。
这是我的代码:
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();
}
}
}
}
编辑:新代码
下载文件并在控制台中打印百分比:D
谢谢大家帮助我!
我是法国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());
}
}
}