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

android按行读取文件内容的几个方法,第1张

概述一、简单版复制代码代码如下: importjava.io.FileInputStream;voidreadFileOnLine(){StringstrFileName=\"Filename.txt\";

一、简单版

复制代码 代码如下:
 import java.io.fileinputStream;
voID readfileOnline(){
String strfilename = "filename.txt";
fileinputStream fis = openfileinput(strfilename);
StringBuffer sBuffer = new StringBuffer();
DatainputStream dataIO = new DatainputStream(fis);
String strline = null;
while((strline =  dataIO.readline()) != null) {
    sBuffer.append(strline + “\n");
}
dataIO.close();
fis.close();
}

二、简洁版

复制代码 代码如下:
//读取文本文件中的内容
    public static String ReadTxtfile(String strfilePath)
    {
        String path = strfilePath;
        String content = ""; //文件内容字符串
            //打开文件
            file file = new file(path);
            //如果path是传递过来的参数,可以做一个非目录的判断
            if (file.isDirectory())
            {
                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,逐行读取文件内容
复制代码 代码如下:
//首先定义一个数据类型,用于保存读取文件的内容
class WeightRecord {
        String timestamp;
        float weight;
        public WeightRecord(String timestamp,float weight) {
            this.timestamp = timestamp;
            this.weight = weight;
           
        }
    }
   
//开始读取
 private WeightRecord[] readLog() throws Exception {
        ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
        file root = Environment.getExternalStorageDirectory();
        if (root == null)
            throw new Exception("external storage dir not found");
        //首先找到文件
        file weightLogfile = new file(root,WeightService.LOGfilePATH);
        if (!weightLogfile.exists())
            throw new Exception("logfile '"+weightLogfile+"' not found");
        if (!weightLogfile.canRead())
            throw new Exception("logfile '"+weightLogfile+"' not readable");
        long modtime = weightLogfile.lastModifIEd();
        if (modtime == lastRecordfileModtime)
            return lastLog;
        // file exists,is readable,and is recently modifIEd -- reread it.
        lastRecordfileModtime = modtime;
        // 然后将文件转化成字节流读取
        fileReader reader = new fileReader(weightLogfile);
        BufferedReader in = new BufferedReader(reader);
        long currentTime = -1;
        //逐行读取
        String line = in.readline();
        while (line != null) {
            WeightRecord rec = parseline(line);
            if (rec == null)
                Log.e(TAG,"Could not parse line: '"+line+"'");
            else if (Long.parseLong(rec.timestamp) < currentTime)
                Log.e(TAG,"ignoring '"+line+"' since it's older than prev log line");
            else {
                Log.i(TAG,"line="+rec);
                result.add(rec);
                currentTime = Long.parseLong(rec.timestamp);
            }
            line = in.readline();
        }
        in.close();
        lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
        return lastLog;
    }
    //解析每一行
    private WeightRecord parseline(String line) {
        if (line == null)
            return null;
        String[] split = line.split("[;]");
        if (split.length < 2)
            return null;
        if (split[0].equals("Date"))
            return null;
        try {
            String timestamp =(split[0]);
            float weight =  float.parsefloat(split[1]) ;
            return new WeightRecord(timestamp,weight);
        }
        catch (Exception e) {
            Log.e(TAG,"InvalID format in line '"+line+"'");
            return null;
        }
    }

2,保存为文件

复制代码 代码如下:
public boolean logWeight(Intent batteryChangeIntent) {
            Log.i(TAG,"logBattery");
            if (batteryChangeIntent == null)
                return false;
            try {
                fileWriter out = null;
                if (mWeightLogfile != null) {
                    try {
                        out = new fileWriter(mWeightLogfile,true);
                    }
                    catch (Exception e) {}
                }
                if (out == null) {
                    file root = Environment.getExternalStorageDirectory();
                    if (root == null)
                        throw new Exception("external storage dir not found");
                    mWeightLogfile = new file(root,WeightService.LOGfilePATH);
                    boolean fileExists = mWeightLogfile.exists();
                    if (!fileExists) {
                        if(!mWeightLogfile.getParentfile().mkdirs()){
                            Toast.makeText(this,"create file Failed",Toast.LENGTH_SHORT).show();
                        }
                        mWeightLogfile.createNewfile();
                    }
                    if (!mWeightLogfile.exists()) {
                        Log.i(TAG,"out = null");
                        throw new Exception("creation of file '"+mWeightLogfile.toString()+"' Failed");
                    }
                    if (!mWeightLogfile.canWrite())
                        throw new Exception("file '"+mWeightLogfile.toString()+"' is not writable");
                    out = new fileWriter(mWeightLogfile,true);
                    if (!fileExists) {
                        String header = createheadline();
                        out.write(header);
                        out.write('\n');
                    }
                }
                Log.i(TAG,"out != null");
                String extras = createBatteryInfoline(batteryChangeIntent);
                out.write(extras);
                out.write('\n');
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                Log.e(TAG,e.getMessage(),e);
                return false;
            }
        }

总结

以上是内存溢出为你收集整理的android按行读取文件内容的几个方法全部内容,希望文章能够帮你解决android按行读取文件内容的几个方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1142422.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存