0
void downloadFile(){
try {
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
// Log.v(imageUrls, "Creating view...");
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
URL url = new URL(imageUrls[pagerPosition]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"image.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB/" + totalSize + "KB (" + (int)per + "%)");
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
}
嗨,我使用這個功能從URL下載圖像工作正常。但它會覆蓋先前下載的圖像..下載圖片覆蓋前一個
File file = new File(SDCardRoot,"image.png");
如何更改名字在上面行每一個新的下載..它不接受任何東西是不是字符串。
任何幫助將是偉大的。
雅感謝ü...這真是棒極了... – diwa
@ user3652550很高興能幫助你。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受,因此可能也會幫助其他人 –
亞我試過了...它要求我等5分鐘才能接受... – diwa