我从asyncTask中的urls下载图像。
我下载了100张图片,其中大约3-4张只是一张黑色图片,看起来下载被中断了或类似的东西。所以照片就像是损坏的文件或者别的什么..。
我真的不明白这一点,因为我有快速稳定的互联网,它只有3-4张图片,总是从100和其他人,不是相同的。
这是我的下载方法:
private void downloadPicture(String strURL, String id) {
id = id.trim();
InputStream input;
try {
URL url = new URL(strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
File DownloadFolder = new File(Environment
.getExternalStorageDirectory().getPath() + "/myTest/");
DownloadFolder.mkdirs();
OutputStream output = new FileOutputStream(
DownloadFolder.toString() + "/" + id + "samplePicture.png");
try {
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
buffer = null;
}
} catch (Exception e) {
Log.e("Exception while grabbing image from URL", e.toString());
}
}我做错了什么?
发布于 2012-12-03 21:38:31
第一件事是,如果你在线程中使用这个函数downloadPicture(String strURL, String id)来并行下载图片,那么使用thread pool,并保持池的大小小于5,这应该是可行的。
发布于 2012-12-03 23:18:47
试试这段代码。
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class ImageManager {
private final String PATH = "/data/data/com.helloandroid.imagedownloader/"; //put the downloaded file here
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL("http://yoursite.com/"" + imageURL); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}https://stackoverflow.com/questions/13684098
复制相似问题