1、文件保存的path
public static final String download_draw_path = new StringBuilder(Environment.getExternalStorageDirectory() .getAbsolutePath()) .append(File.separator).append("TestMxLib").append(File.separator) .toString();
2、判断保存的路径是否存在
public static String isExistDir(String saveDir) throws IOException { // 下载位置 File downloadFile = new File(saveDir); if (!downloadFile.exists()) { downloadFile.mkdirs(); } String savePath = downloadFile.getAbsolutePath(); // LogFileUtil.e("savePath", savePath); return savePath; }
3、okhttp3封装,不再赘述,正常post请求
OkHttp3Util.doPost(url, "", new Callback() { String strRet = ""; public void onFailure(Call call, final IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { long length = response.body().contentLength(); Log.e(Tag, "下载文件," + "文件大小length::" + length); // 判断路径是否存在文件夹 String savePath = isExistDir(Config.download_draw_path); // 文件名,根据具体情况的下载文件类型命名 (.txt .word 等) String fileName = "/test_draw.dwg" File file = new File(savePath,fileName ); Log.e(Tag, "下载文件,getPath>>>" + file.getPath()); // 下面从返回的输入流中读取字节数据并保存为本地文件 try (InputStream is = response.body().byteStream(); FileOutputStream fos = new FileOutputStream(file)) { byte[] buf = new byte[100 * 1024]; int sum = 0, len = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); sum += len; int progress = (int) (sum * 1.0f / length * 100); String detail = String.format("文件保存在%s。已下载%d%%", file.getPath(), progress); Log.e(Tag, "下载图纸,detail>>>" + detail); } Log.e(Tag,"文件下载完毕...."); } catch (Exception e) { e.printStackTrace(); } } });