Android文件下载

public class FileDownloadUtils {

    private String sdPath;

    public FileDownloadUtils() {
        sdPath = Environment.getExternalStorageState() + "/";
    }

    /**
     * 在SD卡上创建文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public File createSDFile(String fileName) throws IOException {
        File file = new File(sdPath + fileName);
        file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName
     * @return
     */
    public File createSDDir(String dirName) {
        File dir = new File(sdPath + dirName);
        dir.mkdirs();
        return dir;
    }

    /**
     * 判断SD卡上的文件夹是否存在
     *
     * @param fileName
     * @return
     */
    public boolean isFileExist(String fileName) {
        File file = new File(sdPath + fileName);
        return file.exists();
    }

    /**
     * 将一个InputStream里面的数据写入到SD卡中
     *
     * @param path
     * @param fileName
     * @param inputStream
     * @return
     */
    public File write2SDFromInput(String path, String fileName, InputStream inputStream) {
        File file = null;
        OutputStream outputStream = null;
        try {
            createSDDir(path);
            file = createSDFile(path + fileName);
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            while ((inputStream.read(buffer)) != -1) {
                outputStream.write(buffer);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    public String getSdPath() {
        return sdPath;
    }

    public void setSdPath(String sdPath) {
        this.sdPath = sdPath;
    }
}

public class HttpDownloader {
    URL url = null;

    public String download(String urlStr) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        BufferedReader br = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 该函数返回整形 -1:代表下载文件出错   0:代表下载文件成功   1:代表文件已经存在
     *
     * @param urlStr
     * @param path
     * @param fileName
     * @return
     */
    public int downFile(String urlStr, String path, String fileName) {
        InputStream inputStream = null;
        try {
            FileDownloadUtils fileDownloadUtils = new FileDownloadUtils();
            if (fileDownloadUtils.isFileExist(path + fileName)) {
                return 1;
            } else {
                inputStream = getInputStreamFromUrl(urlStr);
                File resultFile = fileDownloadUtils.write2SDFromInput(path, fileName, inputStream);
                if (resultFile == null) {
                    return -1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 根据URL得到输入流
     *
     * @param urlStr
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException {
        url = new URL(urlStr);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        return inputStream;
    }

}

在Activity使用:

@Override
    public void onClick(View v) {
        DownloadFileThread downloadFileThread = new DownloadFileThread(downloadUrl, FileUtil.getSDCardPath(), "html.zip");
        downloadFileThread.start();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == -1) {
                Toast.makeText(FileOperateActivity.this, "下载文件出错", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "下载文件出错");
            } else if (msg.what == 0) {
                Toast.makeText(FileOperateActivity.this, "下载文件成功", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "下载文件成功");
            } else if (msg.what == 1) {
                Toast.makeText(FileOperateActivity.this, "代表文件已经存在", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "代表文件已经存在");
            }
        }
    };

    class DownloadFileThread extends Thread {
        private final String download_file_url;
        private final String download_file_path;
        private final String download_file_fileName;

        public DownloadFileThread(String download_file_url, String download_file_path, String download_file_fileName) {
            this.download_file_url = download_file_url;
            this.download_file_path = download_file_path;
            this.download_file_fileName = download_file_fileName;
        }

        @Override
        public void run() {
            HttpDownloader httpDownloader = new HttpDownloader();
            int result = httpDownloader.downFile(download_file_url, download_file_path, download_file_fileName);
            Message message = new Message();
            message.what = result;
            mHandler.sendMessage(message);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值