项目中遇到一个需求,获取服务器返回的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);
}
}