android 下载txt,Android 下载文件(使用OKHttp)

final long startTime = System.currentTimeMillis();

OkHttpClient okHttpClient =new OkHttpClient();

Request request =new Request.Builder()

.url(url)

.addHeader("Connection", "close")

.build();

okHttpClient.newCall(request).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {

Logger.e("@" + e.getMessage());

closeloading();

showShortToast("下载失败");

}

@Override

public void onResponse(Call call, Response response)throws IOException {

showloading("正在下载1%");

InputStream is =null;

byte[] buf =new byte[2048];

int len =0;

FileOutputStream fos =null;

String savePath = Environment.getExternalStorageDirectory().getAbsolutePath(); // 储存下载文件的目录

File filedir =new File(savePath);

if (!filedir.exists()) {

filedir.mkdir();

}

try {

is = response.body().byteStream();

long total = response.body().contentLength();

File file =new File(savePath, fileName);

if (file.exists()) {

file.delete(); // 覆盖(删除原先的文件)

}

fos =new FileOutputStream(file);

long sum =0;

int oldProgress = -1;

while ((len = is.read(buf)) != -1) {

fos.write(buf, 0, len);

sum += len;

int progress = (int) (sum *1.0f / total *100);

if (oldProgress != progress) {

oldProgress = progress;

Logger.i("下载进度" + progress);

showloading("正在下载" + progress + "%");

}

}

fos.flush();

closeloading();

showShortToast("下载完成");

Logger.i("下载完成,用时:" + (System.currentTimeMillis() -startTime));

}catch (Exception e) {

closeloading();

showShortToast("下载失败");

Logger.e("下载失败" + e.getMessage());

}finally {

try {

if (is !=null) {

is.close();

}

}catch (IOException e) {

Logger.e("11" + e.getMessage());

}

try {

if (fos !=null) {

fos.close();

}

}catch (IOException e) {

Logger.e("22" + e.getMessage());

}

}

}

});

你可能感兴趣的:(android,下载txt)