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

43 篇文章 0 订阅

这篇文章主要介绍了android按行读取文件内容的几个方法,java逐行读取文件内容的几个方法,需要的朋友可以参考下

一、简单版

 代码如下:

 
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;
            }
        }


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值