raw 파일에서 큰 파일의 내용을 비동기적으로 읽기

3308 단어 raw
AsyncTask, 비동기 처리, 주로 시간이 많이 걸리는 조작을 주 스레드(UI 스레드)에서 분리하여 처리하고 운행 속도(유창도)를 향상시키는 데 사용된다.AsyncTask를 배우려고 했는데 시간이 걸리는 동작을 보았을 때 큰 파일 읽기 동작을 고려한 다음raw 폴더 아래의 파일을 읽어보았다.
두 가지 방식으로 읽는다. 하나는 줄별로 읽고, 하나는 크기별로 읽는다.
기본 코드는 다음과 같습니다.
1: 줄별 읽기
키 코드:
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();
                }

        }

2: 크기별로 읽기
키 코드:
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();
                }

좋은 웹페이지 즐겨찾기