我开始创建文件下载器类。这是我所拥有的:
public class Downloader {
//download url
URL url;
public Downloader(URL downloadURL){
url = downloadURL;
}
public void toFile(File fName) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fileOutput = new FileOutputStream(fName);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我需要在新线程中调用这个下载器。也许有人可以给我提示为什么我需要为此调用新线程或异步任务。
public void downloadFile(String urlToDownload,String path) throws MalformedURLException{
new Thread(new Runnable() {
public void run() {
new Downloader(new URL(urlToDownload)).toFile(new File(path));
}
}).start();
}
所以当我想下载我的文件时,它表明下载是异步的。
我真的不想那样。 我想创建下载器,我可以在其中选择是同步还是异步下载文件。
但首先,我想知道文件是何时下载的。我怎么会知道这个?
也许有人做过这件事并且可以帮助我。 我需要知道文件何时下载。
谢谢。
最佳答案
关于java - 异步文件下载器android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9885043/