当前位置:  编程技术>移动开发

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

    来源: 互联网  发布时间:2014-10-24

    本文导语:  一、简单版 代码如下:  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...

一、简单版

代码如下:

 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 result = new ArrayList();
        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-metadata
  • android读取assets文件示例
  • android读取raw文件示例
  • android读取sdcard路径下的文件的方法
  • Android读取用户号码,手机串号,SIM卡序列号的实现代码
  • Android 读取Properties配置文件的小例子
  • 基于android中读取assets目录下a.txt文件并进行解析的深入分析
  • android读取Assets图片资源保存到SD卡实例
  • 板子上android读取sd问题
  • android读写sd卡操作写入数据读取数据示例
  • python读取Android permission文件
  • android读取短信示例分享
  • Android中读取中文字符的文件与文件读取相关介绍
  • Android控件ListView用法(读取联系人示例代码)
  • android将图片转换存到数据库再从数据库读取转换成图片实现代码
  • Android提高之SQLite分页读取实现方法
  • 解析Android资源文件及他们的读取方法详解
  • Android创建文件实现对文件监听示例
  • Android文件管理器 雪梦文件管理器
  • Android中删除文件以及文件夹的命令记录
  • Android文件管理器 Astro
  • Android文件管理器 AndFileManage
  • android通过配置文件设置应用安装到SD卡上的方法
  • android开发教程之系统资源的使用方法 android资源文件
  • android保存Bitmap图片到指定文件夹示例
  • Android 工程内嵌资源文件的两种方法
  • android下跑ubuntu下的可执行文件
  • Android递归方式删除某文件夹下的所有文件(.mp3文件等等)
  • android 获取文件的扩展名和去掉文件扩展名的小例子
  • Android 进入设备后台data文件夹的办法
  • android打开rar压缩文件
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 申请Android Map 的API Key(v2)的最新申请方式(SHA1密钥)
  • Android瀑布流实例 android_waterfall
  • Android开发需要的几点注意事项总结
  • Android系统自带样式 (android:theme)
  • android 4.0 托管进程介绍及优先级和回收机制
  • Android网络共享软件 Android Wifi Tether
  • Android访问与手机通讯相关类的介绍
  • Android 图标库 Android GraphView
  • Android及andriod无线网络Wifi开发的几点注意事项
  • 轻量级Android开发工具 Android Tools
  • Android 2.3 下StrictMode介绍
  • Android 开发环境 Android Studio
  • IDEA的Android开发插件 idea-android
  • Android手机事件提醒 Android Notifier
  • XBMC的Android客户端 android-xbmcremote
  • Android小游戏 Android Shapes
  • Android电池监控 Android Battery Dog
  • android开发:“android:WindowTitle”没有对应项no resource
  • Android 上类似IOS 的开关控件。 Android ToggleButton
  • Android 将 android view 的位置设为右下角的解决方法
  • Android 2D游戏引擎 Android Angle


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3