当前位置: 首页 > 编程笔记 >

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

锺离飞尘
2023-03-14
本文向大家介绍android按行读取文件内容的几个方法,包括了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;

            }

        }

 类似资料:
  • 本文向大家介绍PowerShell读取文本文件指定行内容的方法,包括了PowerShell读取文本文件指定行内容的方法的使用技巧和注意事项,需要的朋友参考一下 本文介绍一个PowerShell中如何一步到位的获取到一个文本文件的第N行。比如一个文本文件,它有1000行,我想把第500行的内容直接取出来的,最简单的方法是通过PowerShell来实现。 在PowerShell中,可以通过Get-Co

  • 本文向大家介绍jQuery读取XML文件内容的方法,包括了jQuery读取XML文件内容的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了jQuery读取XML文件内容的方法。分享给大家供大家参考。具体实现方法如下: 希望本文所述对大家的jQuery程序设计有所帮助。

  • 本文向大家介绍python读取几个G的csv文件方法,包括了python读取几个G的csv文件方法的使用技巧和注意事项,需要的朋友参考一下 如下所示: 以上这篇python读取几个G的csv文件方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 返回一个数组,数组中每个元素是指定文件中的每一行。 在 fs node 包中使用 readFileSync 函数指定文件中创建一个 Buffer 。使用 toString(encoding) 函数将 buffer 转换为字符串。通过逐行 split 文件内容(每个\n)根据文件内容创建一个数组。 const fs = require('fs'); const readFileLines = fil

  • 逐行读取文本文件的内容,每次一行(比 FileReadLine 执行的更好)。 Loop, Read, InputFile [, OutputFile] 参数 Read 此参数必须为单词 READ. InputFile 需要在循环中读取内容的文本文件的名称, 如果未指定绝对路径则假定在 %A_WorkingDir% 中. 支持 Windows 和 Unix 格式; 即文件的行结束符可以是回车和换行

  • 本文向大家介绍Python按行读取文件的实现方法【小文件和大文件读取】,包括了Python按行读取文件的实现方法【小文件和大文件读取】的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Python按行读取文件的实现方法。分享给大家供大家参考,具体如下: 小文件: 大文件: 更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操