AsyncTask,异步处理,主要用于将比较耗时的操作从主线程(UI线程)中分离出来处理,提高运行速度(流畅度)。本来是要学习AsyncTask的,当看到耗时操作时就考虑到了读取大文件操作,然后自己试着读取raw文件夹下面的文件。
有两种方式读取,一种是按行读取,一种是按大小读取;
主要代码如下:
一:按行读取
关键代码:
class FileReadTask extends AsyncTask<String, String, String> {
String line_str;
String result;
Context context;
FileReadTask(Context context) {
this.context = context;
}
int i = 0;
@Override
protected String doInBackground(String... params) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
context.getResources().openRawResource(R.raw.test2)));
try {
while ((line_str = reader.readLine()) != null
&& !(line_str = reader.readLine()).equals("")) {
result += line_str;
System.out.println("line_str:"+line_str);
publishProgress(line_str);
}
System.out.println("result:"+result);
} catch (IOException e) {
e.printStackTrace();
}
return line_str;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values[0]);
System.out.println("values:" + values[0]);
array.add(values[0]);
adapter.notifyDataSetChanged();
}
}
二:按大小读取
关键代码:
InputStream input = context.getResources().openRawResource(R.raw.test2);
String result = null;
int i;
byte[] by = new byte[128];//每次读取大小
try {
while((i = input.read(by))>0){
byte[] bys = new byte[i];
input.read(bys,0,i);
String s = new String(bys);
result +=s;
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
标签:文件,context,下大,String,raw,result,str,line,读取
From: https://blog.51cto.com/u_5454003/6174159