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

一、简单版

 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         }
时间: 2024-08-05 11:17:49

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

Python跳过第一行读取文件内容

Python编程时,经常需要跳过第一行读取文件内容.比较容易想到是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作.相应的Python代码如下: [python] view plain copy input_file = open("C:\\Python34\\test.csv") line_num = 0 for line in islice(input_file, 1, None): line_num += 1 if (line_num

23 遍历删除本地目录的方法,文件末尾追加内容,按行读取文件内容

1.遍历删除本地目录 /** * 递归删除非空目录 * @param file */ public static void deletNotEmptyDir(File file){ File[] files = file.listFiles(); if (files != null) { for (File f : files) { deletNotEmptyDir(f); } } file.delete(); } 2.文件末尾追加内容 /** * 在文件末尾追加字符串 * @param fil

B.php中读取文件内容的几种方法

php中读取文件内容的几种方法 1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件中读取最多 length 个字节.该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况. fread() 返回所读取的字符串,如果出错返回 FALSE. <?php $filename

研究MapReduce源码之实现自定义LineRecordReader完成多行读取文件内容

TextInputFormat是Hadoop默认的数据输入格式,但是它只能一行一行的读记录,如果要读取多行怎么办? 很简单 自己写一个输入格式,然后写一个对应的Recordreader就可以了,但是要实现确不是这么简单的 首先看看TextInputFormat是怎么实现一行一行读取的 大家看一看源码 public class TextInputFormat extends FileInputFormat<LongWritable, Text> { @Override public Record

php中读取文件内容的几种方法

1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件中读取最多 length 个字节.该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况. fread() 返回所读取的字符串,如果出错返回 FALSE. <?php $filename = "/usr/loca

2、python逐行读取文件内容的三种方法

方法一: 复制代码代码如下: f = open("foo.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 # print(line, end = '') # 在 Python 3 中使用 line = f.readline() f.close() 方法二: 复制代码代码如下: for line in open("foo.txt&

python逐行读取文件内容的三种方法

方法一: f = open("foo.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 # print(line, end = '') # 在 Python 3中使用 line = f.readline() f.close() 方法二: for line in open("foo.txt"): print line, 方

php读取文件内容的三种方法

<?php //**************第一种读取方式***************************** 代码如下: header("content-type:text/html;charset=utf-8"); //文件路径 $file_path = "text.txt"; //判断是否有这个文件 if (file_exists($file_path)) { if ($fp = fopen($file_path, "a+"))

shell脚本按行读取文件内容的方法

方法1: exec <file sum=0 while read line;do cmd done 方法2: cat ${FILE_PATH} |while read line do cmd done 方法3: while read line do cmd done<FILE