异步读取文件实例

1、目的:

通过异步的方式,读取sdcard中的文件,并显示读取进度,最后将读取的文件显示在指定的位置

2、代码

  1 package com.example.myfile;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.InputStreamReader;
 10 import java.io.Reader;
 11 
 12 import org.apache.http.util.EncodingUtils;
 13 
 14 import android.os.AsyncTask;
 15 import android.os.Bundle;
 16 import android.app.Activity;
 17 import android.app.ProgressDialog;
 18 import android.content.Context;
 19 import android.text.InputFilter;
 20 import android.view.Menu;
 21 import android.widget.ProgressBar;
 22 import android.widget.TextView;
 23 
 24 public class MainActivity extends Activity {
 25     TextView tv;
 26     ProgressDialog pd;
 27     class ReadFile extends AsyncTask<File, Integer, String>{
 28         int progress = 0;
 29         Context ctx;
 30         public ReadFile(Context ctx){
 31             this.ctx = ctx;
 32         }
 33         @Override
 34         protected String doInBackground(File... params) {
 35             // TODO Auto-generated method stub
 36             StringBuilder sb = new StringBuilder();
 37             String text = null;
 38             try {
 39                 FileInputStream file = new FileInputStream(params[0]);
 40                 BufferedReader br = new BufferedReader(new InputStreamReader(file));
 41                 while((text = br.readLine())!=null){
 42                     sb.append(text+"\n");
 43                     progress++;
 44                     publishProgress(progress);
 45                 }
 46                 text = sb.toString();
 47             }catch(Exception e){
 48                 e.printStackTrace();
 49             }
 50             System.err.println(text);
 51             return text;
 52         }
 53 
 54         @Override
 55         protected void onPostExecute(String result) {
 56             // TODO Auto-generated method stub
 57             System.err.println(result);
 58             tv.setText(result);
 59             pd.dismiss();
 60         }
 61 
 62         @Override
 63         protected void onPreExecute() {
 64             // TODO Auto-generated method stub
 65             pd = new ProgressDialog(ctx);
 66             pd.setTitle("正在加载中");
 67             pd.setMessage("文件正在加载,已加载");
 68             pd.setIndeterminate(false);
 69             pd.setCancelable(false);
 70             pd.setMax(148);
 71             //很重要,默认的是STYLE_SPINNER,不会显示已加载了多少!
 72             pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
 73             pd.setProgress(progress);
 74             pd.show();
 75         }
 76 
 77         @Override
 78         protected void onProgressUpdate(Integer... values) {
 79             // TODO Auto-generated method stub
 80             pd.setProgress(values[0]);
 81         }
 82         
 83     }
 84     @Override
 85     protected void onCreate(Bundle savedInstanceState) {
 86         super.onCreate(savedInstanceState);
 87         setContentView(R.layout.activity_main);
 88         tv = (TextView)findViewById(R.id.text);
 89         String filename = "/sdcard/myfile.txt";
 90         ReadFile rf = new ReadFile(this);
 91         rf.execute(new File(filename));
 92         
 93     }
 94 
 95     @Override
 96     public boolean onCreateOptionsMenu(Menu menu) {
 97         // Inflate the menu; this adds items to the action bar if it is present.
 98         getMenuInflater().inflate(R.menu.main, menu);
 99         return true;
100     }
101 
102 }

3、总结

  3.1  AsyncTask代码简单,将方法重写即可。

  3.2  关于文件读取,参考此文http://www.cnblogs.com/freeliver54/archive/2011/09/16/2178910.html

    1>  读写sdcard里的文件首先要将电脑中的文件复制到sdcard中,方法:

    sdk tools 文件夹中有adb.exe,或者在platform-tools中,如果在环境变量path中已经加入了adb所在文件夹的路径,就可打开cmd后直接执行命令adb.exe push     e:/Y.txt /sdcard/(注意最后一个斜杠,如果没有会报错);如果没有加入环境变量,就进入相应的目录后执行命令。  另:把仿真器上的文件copy到本地计算机上用: adb pull ./data/data/com.tt/files/Test.txt e:/

    2> 文件在sdcard中时,读写文件用FileInputScream()和FilePutputScream(),代码如下:

 

 

 1 String fileName = "/sdcard/Y.txt";
 2 
 3 //也可以用String fileName = "mnt/sdcard/Y.txt";
 4 
 5 String res="";     
 6 try{ 
 7     FileInputStream fin = new FileInputStream(fileName);
 8     int length = fin.available(); 
 9     byte [] buffer = new byte[length]; 
10     fin.read(buffer);     
11     res = EncodingUtils.getString(buffer, "UTF-8"); 
12     fin.close();     
13     }catch(Exception e){ 
14            e.printStackTrace(); 
15 } 
16 myTextView.setText(res);

    3>  文件在data/data/目录下时,用openFileOutput()和openFileInput,代码如下:

 public voidwriteFileData(String fileName,String message){ 
       try{ 
        FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);

        byte [] bytes = message.getBytes(); 
        fout.write(bytes); 
         fout.close(); 
        } 
       catch(Exception e){ 
        e.printStackTrace(); 
       } 
   }

  4>  文件在raw目录下时,R中有记录,

  InputScream in = getResource().openRawResource(R.raw.filename);

  5>  文件在asset目录下时,

  InputScream in = getResource().getAssets().open(filename);

注: openFileOutput是在raw里编译过的,FileOutputStream是任何文件都可以

 

posted @ 2014-03-20 10:48  小Garfield  阅读(832)  评论(0编辑  收藏  举报