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

一、简单版



代码如下:

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)

相关推荐

  • Android 解析XML 文件的四种方法总结

    java解析xml文件四种方式 1.介绍 1)DOM(JAXP Crimson解析器) DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找特定信息.分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作.由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的.DOM以及广义的基于树的处理具有几个优点.首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改.它还可以

  • android读取sdcard路径下的文件的方法

    复制代码 代码如下: // 读取sdcard文件private void sdcardRead(){String fileName = "/sdcard/my_sdcard.txt";// assets下文件//String fileName = "/sdcard/test/my_sdcard_test.txt";// sdcard下子目录文件String ret = "";try {FileInputStream fis = new FileI

  • android读取assets文件示例

    复制代码 代码如下: // 读取assets文件private void assetsRead(){String fileName = "my_assets.txt";// assets下文件//String fileName = "test/my_assets_test.txt";// assets下子目录文件String ret = "";try {InputStream is = getResources().getAssets().ope

  • Android应用程序中读写txt文本文件的基本方法讲解

    最终效果图,点击save会保存到文件中,点击show会从文件中读取出内容并显示. main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layou

  • 解析Android资源文件及他们的读取方法详解

    Sam在Android开发中,有两种处理资源文件的方式.其一,是将所有资源文件以及JNI程序放置于一个单独的资源包.使用到他们时,使用文件方式读取.或者直接使用C++层代码读取. 其二,则是将资源文件加入到APK内部.使用各种不同的办法去得到其内容.方法一:适合于移植较大的C++程序时使用,因为C++代码数量众多,不太可能修改为JAVA代码.所以将其与资源文件以一定方式存放,并让他们自称体系是个好办法.但这造成软件的发布必须以APK+资源包的方式发布.方法二:则比较适合代码量不是非常大,且资源数

  • Android开发实现Files文件读取解析功能示例

    本文实例讲述了Android开发实现Files文件读取解析功能.分享给大家供大家参考,具体如下: package com.example.file; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widg

  • android读取raw文件示例

    复制代码 代码如下: // 读取raw文件private void rawRead(){String ret = "";try {InputStream is = getResources().openRawResource(R.raw.my_raw);int len = is.available();byte []buffer = new byte[len];is.read(buffer);ret = EncodingUtils.getString(buffer, "utf

  • Android应用读取Excel文件的方法

    本文实例讲述了Android应用读取Excel文件的方法.分享给大家供大家参考,具体如下: ReadExcel.java文件: public class ReadExcel extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)

  • android编程之xml文件读取和写入方法

    本文实例讲述了android编程之xml文件读取和写入方法.分享给大家供大家参考.具体分析如下: 一.环境: 主机:WIN8 开发环境:Eclipse 二.说明: 1.打开sd卡中的xml文件,如果不存在,这新建一个,并写入默认配置 2.读取xml文件 三.xml文件格式: <?xml version="1.0" encoding="UTF-8" standalone="true"?> -<config> <titl

  • 基于android中读取assets目录下a.txt文件并进行解析的深入分析

    android读取assets文件下的内容,一般都是使用getAsset.open()方法,并将文件的路径作为参数传入,而当我们解析一个目录下的文件时需要对其进行解析时,比如:a.txt文件的内容为:nameandroid,liuclass1,2,3,4这些文件有时就像是数据库文件的格式一样,我们就需要对其进行解析.我们知道获取assets文件后返回的是一个inputstream而不是一个file类型,所以我们需要对inputstream进行解析.主要分为两个阶段:第一个阶段为:去换行符,第二个

随机推荐