import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.pupuwang.sjzx.home.AddShopUploadPicActivity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class AsynFileDownLoader {
private ExecutorService mPool;//线程池对象
private AddShopUploadPicActivity mAct;
public AsynFileDownLoader(AddShopUploadPicActivity act) {
mPool = Executors.newFixedThreadPool(5);//线程池缓存线程数
mAct = act;
}
/**
*
* @param position
* @param type
* @param url
* @param path
* @param fileName
* 2013-12-2
* 下午3:46:13
* Administrator
*/
public void downFile(final int position, final int type, final String url,final Handler handler,
final String path, final String fileName) {
mPool.submit(new Runnable() {
@Override
public void run() {
try {
Message msg = new Message();
msg.arg1 = position;
msg.arg2 = type;
Utils.downFile(url, path, fileName, handler,msg);
} catch (IOException e) {
e.printStackTrace();
Log.e("AsynFileDownLoader", e.toString());
}
}
});
}
}
public static void downFile(String url, String path, String fileName , Handler handler,Message msg) throws IOException {
String name = "";
if (fileName == null || fileName == "")
name = url.substring(url.lastIndexOf("/") + 1);
else
name = fileName; // 取得文件名,如果输入新文件名,则使用新文件名
URL Url = new URL(url);
URLConnection conn = Url.openConnection();
conn.connect();
conn.setConnectTimeout(5*1000);
InputStream is = conn.getInputStream();
if (is == null) { // 没有下载流
msg.what = 0x1100;
handler.sendMessage(msg);
throw new RuntimeException("无法获取文件");
}
FileOutputStream fos = new FileOutputStream(path +"/"+ name); // 创建写入文件内存流,
// 通过此流向目标写文件
byte[] buf = new byte[1024];
int downLoadFilePosition = 0;
int numread = 0;
while ((numread = is.read(buf)) != -1) {
fos.write(buf,0,numread);
downLoadFilePosition += numread;
}
try {
is.close();
fos.flush();
fos.close();
msg.what = 0x1101;
handler.sendMessage(msg);
} catch (Exception ex) {
Log.e("MyTextUtils", ex.toString());
msg.what = 0x1100;
handler.sendMessage(msg);
}
}
转载于:https://blog.51cto.com/lyp634959848/1335612