Android 线程AsyncTask+EventBus实现下载CSV文件

项目中遇到一个需求,获取服务器返回的csv文件路径,下载到手机本地。然后将本地文件读成字符流,解析显示。

 

代码说明

 

1.自定义AsyncTask类

/**
 * 任务列表下载CSV文件AsyncTask
 */

public class DownLoadRenWuTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private ProgressDialog procDialog;
    private String filename;

    /**
     * 构造方法
     */

    public DownLoadRenWuTask(Context context, ProgressDialog procDialog, String filename) {
        this.context = context;
        this.procDialog = procDialog;
        this.filename = filename;
    }

    /**
     * doInBackground方法 后台执行耗时方法 下载文件
     */

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {//相应失败
                return "server returned HTTP:" + connection.getResponseCode() + "" + connection.getResponseMessage();
            }
            int fileLength = connection.getContentLength();
            input = connection.getInputStream();
            if (BooleanUtils.isEmpty(filename)) {
                filename = System.currentTimeMillis() + ".csv";
            }
            output = new FileOutputStream(FileHelper.getTheRootDirectory() + StringConstant.RenWu_Path + filename);
            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                if (fileLength > 0) {
                    //publishing hte progress...
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
                if (null != input) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (null != connection) {
                connection.disconnect();
            }
        }

        return null;
    }

    /**
     * onPreExecute方法 准备工作
     */

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.acquire();
        procDialog.show();
    }

    /**
     * onProgressUpdate方法 更新进度
     */

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        procDialog.setIndeterminate(false);
        procDialog.setMax(100);
        procDialog.setProgress(progress[0]);
    }

    /**
     * onPostExecute方法 更新结果
     */

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        mWakeLock.release();
        procDialog.dismiss();
        //发送EventBus通知 刷新任务详情模块
        EventBusBean eventBusBean = new EventBusBean();
        eventBusBean.setUpdatetype(result);
        eventBusBean.setContext(filename);
        EventBus.getDefault().post(eventBusBean);
    }

}

 

 

2. Activity接收

 /**
     * onEventMainThread EventBus
     * */

    public void onEventMainThread(EventBusBean eventBusBean) {
        if (null != eventBusBean) {
            String type=eventBusBean.getUpdatetype();
            String filepath=eventBusBean.getContext();
            if(!BooleanUtils.isEmpty(type)){
                toast.showToast(StringConstant.renwuststatus10);
            }else{
                if(!BooleanUtils.isEmpty(filepath)&&null!=file&&!BooleanUtils.isEmpty(createfile)){
                    boolean isExist = FileHelper.isExistFile(file, filepath);
                    if (isExist) {//文件已存在
                        showViewData(createfile,filepath);
                        toast.showToast(StringConstant.renwuststatus5);
                    } else {//文件 不存在
                        loadCSVFile();
                    }
                }
            }
        }
    }

 

 

3.解析文件转换成字符流

 /**
     * 获取字符流解析CSV文件
     * */

    private void showViewData(final String createfile,final String filepath){
        showProgressDialogs();
        try {
            //1.获取字符流
            File csvfile = new File(createfile, filepath);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(csvfile), "gb2312");
            BufferedReader br = new BufferedReader(isr);
            //2.读取标题
            firstline = br.readLine();
            if (!BooleanUtils.isEmpty(firstline)) {
                String firststring[] = firstline.split(",", -1);
                if (null != firststring) {
                    int firstnum = firststring.length;
                    if(firstnum>0){
                        lists.removeAll(lists);
                        lists.add(firststring);//先将标题加入到集合
                        //3.读取内容
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            if (!BooleanUtils.isEmpty(line)) {
                                String string[] = line.split(",", -1);
                                int num=string.length;
                                if(num==firstnum&&BooleanUtils.isStringHaveElement(string)){
                                    lists.add(string);//将合法的内容加入到集合
                                }
                            }
                        }
                    }
                }
            }
            br.close();
        } catch (Exception e) {
            // 捕获File对象生成时的异常
            e.printStackTrace();
        }

        if (lists.size() > 0) {//有数据
            scrollview.setVisibility(View.VISIBLE);
            nodatetextview.setVisibility(View.GONE);
            initData(lists);
        } else {
            dismissProgressDialogs();
            scrollview.setVisibility(View.GONE);
            nodatetextview.setVisibility(View.VISIBLE);
            nodatetextview.setText(StringConstant.renwuststatus4);
            numberlinearlayout.setVisibility(View.GONE);
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值