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

 更新时间:2014年06月27日 11:45:03   投稿:junjie  
这篇文章主要介绍了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;
            }
        }

相关文章

  • Android自定义view仿微信刷新旋转小风车

    Android自定义view仿微信刷新旋转小风车

    这篇文章主要介绍了Android自定义view仿微信刷新旋转小风车,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • Android开发中PopupWindow用法实例分析

    Android开发中PopupWindow用法实例分析

    这篇文章主要介绍了Android开发中PopupWindow用法,结合实例形式分析了PopupWindow弹出窗口效果的使用技巧,需要的朋友可以参考下
    2016-02-02
  • Android Studio实现帧动画

    Android Studio实现帧动画

    这篇文章主要为大家详细介绍了Android Studio实现帧动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • Android 手写热修复dex实例详解

    Android 手写热修复dex实例详解

    这篇文章主要为大家介绍了Android 手写热修复dex实现示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • Flutter项目在 iOS14 启动崩溃的解决方法

    Flutter项目在 iOS14 启动崩溃的解决方法

    这篇文章主要介绍了Flutter项目在 iOS14 启动崩溃的解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • 基于Vert.x和RxJava 2构建通用的爬虫框架的示例

    基于Vert.x和RxJava 2构建通用的爬虫框架的示例

    这篇文章主要介绍了基于Vert.x和RxJava 2构建通用的爬虫框架的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • Android短信验证码(用的Mob短信验证)

    Android短信验证码(用的Mob短信验证)

    这篇文章主要为大家详细介绍了Android短信验证码,使用Mob短信验证,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • 浅谈Android Classloader动态加载分析

    浅谈Android Classloader动态加载分析

    这篇文章主要介绍了浅谈Android Classloader动态加载分析,详细的介绍了ClassLoader概念、分类,具有一定的参考价值,有兴趣的可以了解一下
    2018-03-03
  • Android自定义view实现太极效果实例代码

    Android自定义view实现太极效果实例代码

    这篇文章主要介绍了Android自定义view实现太极效果实例代码的相关资料,需要的朋友可以参考下
    2017-05-05
  • Android编程实现监控各个程序流量的方法

    Android编程实现监控各个程序流量的方法

    这篇文章主要介绍了Android编程实现监控各个程序流量的方法,涉及Android针对应用包的遍历,权限控制及相关属性操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-12-12

最新评论