我正在尝试使用以下代码下载一个 exe 文件,知道为什么它只下载了大约 30% 的文件吗?至少它不会抛出任何异常。
我的主要方法如下所示: new DownloadWorker().execute();
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.SwingWorker;
public final class DownloadWorker extends SwingWorker<Object, Object> {
@Override
protected Object doInBackground() throws Exception {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
URL url = new URL("http://download.piriform.com/ccsetup320.exe");
URLConnection conn = url.openConnection();
conn.connect();
int fileLength = conn.getContentLength();
in = new BufferedInputStream(url.openStream());
out = new BufferedOutputStream(new FileOutputStream("ccsetup320.exe"));
byte[] buffer = new byte[4096];
long total = 0;
int bytesRead = 0;
while ( (bytesRead = in.read(buffer)) != -1 ) {
total += bytesRead;
System.out.println((int) (total * 100 / fileLength));
out.write(buffer, 0, bytesRead);
}
} catch ( Exception e ) {
e.printStackTrace();
} finally {
if ( out != null ) {
out.flush();
out.close();
}
if ( in != null ) {
in.close();
}
}
return null;
}
@Override
protected void done() {
}
}
谢谢。