码迷,mamicode.com
首页 > 移动开发 > 详细

android按行读取文件内容的几个方法

时间:2014-12-28 16:45:44      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:

一、简单版

 1 import java.io.FileInputStream;
 2 void readFileOnLine(){
 3     String strFileName = "Filename.txt";
 4     FileInputStream fis = openFileInput(strFileName);
 5     StringBuffer sBuffer = new StringBuffer();
 6     DataInputStream dataIO = new DataInputStream(fis);
 7     String strLine = null;
 8     while((strLine =  dataIO.readLine()) != null) {
 9         sBuffer.append(strLine + “\n");
10     }
11     dataIO.close();
12     fis.close();
13 }

 二、简洁版

public static String ReadTxtFile(String strFilePath)
    {
            String path = strFilePath;
            String content = "";     //文件内容字符串
            File file = new File(path);    //打开文件
            
            if (file.isDirectory())    //如果path是传递过来的参数,可以做一个非目录的判断
            {
                Log.d("TestFile", "The File doesn‘t not exist.");
            }
            else
            {
                try {
                    InputStream instream = new FileInputStream(file); 
                    if (instream != null) 
                    {
                        InputStreamReader inputreader = new InputStreamReader(instream);
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line;
                        //分行读取
                        while (( line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }                
                        instream.close();
                    }
                }
                catch (java.io.FileNotFoundException e) 
                {
                    Log.d("TestFile", "The File doesn‘t not exist.");
                } 
                catch (IOException e) 
                {
                     Log.d("TestFile", e.getMessage());
                }
            }
            return content;
    }

 三、用于长时间使用的apk,并且有规律性的数据

1,逐行读取文件内容

 1 //首先定义一个数据类型,用于保存读取文件的内容 
 2 class WeightRecord {
 3         String timestamp;
 4         float weight;
 5         public WeightRecord(String timestamp, float weight) {
 6             this.timestamp = timestamp;
 7             this.weight = weight;
 8             
 9         }
10     }
11     
12 //开始读取
13  private WeightRecord[] readLog() throws Exception {
14         ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
15         File root = Environment.getExternalStorageDirectory();
16         if (root == null)
17             throw new Exception("external storage dir not found");
18         //首先找到文件
19         File weightLogFile = new File(root,WeightService.LOGFILEPATH);
20         if (!weightLogFile.exists())
21             throw new Exception("logfile ‘"+weightLogFile+"‘ not found");
22         if (!weightLogFile.canRead())
23             throw new Exception("logfile ‘"+weightLogFile+"‘ not readable");
24         long modtime = weightLogFile.lastModified();
25         if (modtime == lastRecordFileModtime)
26             return lastLog;
27         // file exists, is readable, and is recently modified -- reread it.
28         lastRecordFileModtime = modtime;
29         // 然后将文件转化成字节流读取
30         FileReader reader = new FileReader(weightLogFile);
31         BufferedReader in = new BufferedReader(reader);
32         long currentTime = -1;
33         //逐行读取
34         String line = in.readLine();
35         while (line != null) {
36             WeightRecord rec = parseLine(line);
37             if (rec == null)
38                 Log.e(TAG, "could not parse line: ‘"+line+"‘");
39             else if (Long.parseLong(rec.timestamp) < currentTime)
40                 Log.e(TAG, "ignoring ‘"+line+"‘ since it‘s older than prev log line");
41             else {
42                 Log.i(TAG,"line="+rec);
43                 result.add(rec);
44                 currentTime = Long.parseLong(rec.timestamp);
45             }
46             line = in.readLine();
47         }
48         in.close();
49         lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
50         return lastLog;
51     }
52     //解析每一行
53     private WeightRecord parseLine(String line) {
54         if (line == null)
55             return null;
56         String[] split = line.split("[;]");
57         if (split.length < 2)
58             return null;
59         if (split[0].equals("Date"))
60             return null;
61         try {
62             String timestamp =(split[0]);
63             float weight =  Float.parseFloat(split[1]) ;
64             return new WeightRecord(timestamp,weight);
65         }
66         catch (Exception e) {
67             Log.e(TAG,"Invalid format in line ‘"+line+"‘");
68             return null;
69         }
70     }

 2,保存为文件

 1 public boolean logWeight(Intent batteryChangeIntent) {
 2             Log.i(TAG, "logBattery");
 3             if (batteryChangeIntent == null)
 4                 return false;
 5             try {
 6                 FileWriter out = null;
 7                 if (mWeightLogFile != null) {
 8                     try {
 9                         out = new FileWriter(mWeightLogFile, true);
10                     }
11                     catch (Exception e) {}
12                 }
13                 if (out == null) {
14                     File root = Environment.getExternalStorageDirectory();
15                     if (root == null)
16                         throw new Exception("external storage dir not found");
17                     mWeightLogFile = new File(root,WeightService.LOGFILEPATH);
18                     boolean fileExists = mWeightLogFile.exists();
19                     if (!fileExists) {
20                         if(!mWeightLogFile.getParentFile().mkdirs()){
21                             Toast.makeText(this, "create file failed", Toast.LENGTH_SHORT).show();
22                         }
23                         mWeightLogFile.createNewFile();
24                     }
25                     if (!mWeightLogFile.exists()) {
26                         Log.i(TAG, "out = null");
27                         throw new Exception("creation of file ‘"+mWeightLogFile.toString()+"‘ failed");
28                     }
29                     if (!mWeightLogFile.canWrite()) 
30                         throw new Exception("file ‘"+mWeightLogFile.toString()+"‘ is not writable");
31                     out = new FileWriter(mWeightLogFile, true);
32                     if (!fileExists) {
33                         String header = createHeadLine();
34                         out.write(header);
35                         out.write(‘\n‘);
36                     }
37                 }
38                 Log.i(TAG, "out != null");
39                 String extras = createBatteryInfoLine(batteryChangeIntent);
40                 out.write(extras);
41                 out.write(‘\n‘);
42                 out.flush();
43                 out.close();
44                 return true;
45             } catch (Exception e) {
46                 Log.e(TAG,e.getMessage(),e);
47                 return false;
48             }
49         }

 

android按行读取文件内容的几个方法

标签:

原文地址:http://www.cnblogs.com/maoIT/p/4190082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!