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

时间: 2024-10-07 05:40:17

android按行读取文件内容的几个方法_Android的相关文章

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

一.简单版 复制代码 代码如下:  import java.io.FileInputStream; void readFileOnLine(){ String strFileName = "Filename.txt"; FileInputStream fis = openFileInput(strFileName); StringBuffer sBuffer = new StringBuffer(); DataInputStream dataIO = new DataInputStre

php读取文件内容到数组的方法

这篇文章主要介绍了php读取文件内容到数组的方法,涉及php中file.rtrim等函数对文件及字符串的操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下     本文实例讲述了php读取文件内容到数组的方法.分享给大家供大家参考.具体分析如下: php中可以通过file()函数将文件读取到数组中,数组中的元素即为文件的每行,file()函数通过"n"按行分割文件保存到数组,所以数组每个元素都是以"n"结尾,我们可以通过 rtrim()函数将其去除 ? 1 2 3

php读取文件内容到数组的方法_php技巧

本文实例讲述了php读取文件内容到数组的方法.分享给大家供大家参考.具体分析如下: php中可以通过file()函数将文件读取到数组中,数组中的元素即为文件的每行,file()函数通过"\n"按行分割文件保存到数组,所以数组每个元素都是以"\n"结尾,我们可以通过 rtrim()函数将其去除 <?php $lines = file("/tmp/file.txt"); foreach ($lines as $line) { $line = r

php读取文件内容的三种方法

 这篇文章主要介绍了php读取文件内容的三种方法,需要的朋友可以参考下 php读取文件内容的三种方法:    //**************第一种读取方式*****************************  代码如下: header("content-type:text/html;charset=utf-8");  //文件路径  $file_path="text.txt";  //判断是否有这个文件  if(file_exists($file_path)

android从资源文件中读取文件流并显示的方法_Android

本文实例讲述了android从资源文件中读取文件流并显示的方法.分享给大家供大家参考.具体如下: 在android中,假如有的文本文件,比如TXT放在raw下,要直接读取出来,放到屏幕中显示,可以这样: private void doRaw(){ InputStream is = this.getResources().openRawResource(R.raw.ziliao); try{ doRead(is); }catch(IOException e){ e.printStackTrace(

Java文件操作之按行读取文件和遍历目录的方法_java

按行读取文件 package test; import java.io.*; import java.util.*; public class ReadTest { public static List<String> first_list; public static List<String> second_list; public ReadTest() { first_list = new LinkedList<>(); second_list = new Link

Android编程实现读取本地SD卡图片的方法_Android

本文实例讲述了Android编程实现读取本地SD卡图片的方法.分享给大家供大家参考,具体如下: private Bitmap getDiskBitmap(String pathString) { Bitmap bitmap = null; try { File file = new File(pathString); if(file.exists()) { bitmap = BitmapFactory.decodeFile(pathString); } } catch (Exception e)

php读取文件内容的几种方法详解

示例代码1: 用file_get_contents 以get方式获取内容 复制代码 代码如下: <?php $url='http://www.baidu.com/'; $html=file_get_contents($url); //print_r($http_response_header); ec($html); printhr(); printarr($http_response_header); printhr(); ?> 示例代码2: 用fopen打开url, 以get方式获取内容

php读取文件内容几种正确方法

//方法一 用while来些fgets一行行读 $file_name="1.txt";  代码如下 复制代码 $fp=fopen($file_name,'r');  while(!feof($fp))  {   $buffer=fgets($fp,4096);   echo $buffer."<br>";  }  fclose($fp);   // 方法二 用file一次保存到数组再用foreach输出  代码如下 复制代码 $array = file(