一、简单版

 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); //打开文件 if (file.isDirectory()) //如果path是传递过来的参数,可以做一个非目录的判断
{
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按行读取文件内容的几个方法的更多相关文章

  1. Python跳过第一行读取文件内容

    Python编程时,经常需要跳过第一行读取文件内容.比较容易想到是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作.相应的Python代码如下: inpu ...

  2. php中读取文件内容的几种方法。(file_get_contents:将文件内容读入一个字符串)

    php中读取文件内容的几种方法.(file_get_contents:将文件内容读入一个字符串) 一.总结 php中读取文件内容的几种方法(file_get_contents:将文件内容读入一个字符串 ...

  3. 【Shell】按行读取文件内容

    方法1:while循环中执行效率最高,最常用的方法. function while_read_LINE_bottm(){ While read LINE do echo $LINE done < ...

  4. php中读取文件内容的几种方法

    1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件中读取最多 length 个字节.该函数在读取完最多 ...

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

    <?php //**************第一种读取方式***************************** 代码如下: header("content-type:text/h ...

  6. [转]Python跳过第一行读取文件内容

    from itertools import islice file_name='XXXX' input_file = open(file_name) for line in islice(input_ ...

  7. C++/Php/Python/Shell 程序按行读取文件或者控制台

    写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下.方便使用 1. C++ 读取文件 #include<stdio.h> #include<string.h> i ...

  8. C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。

    C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结. 一.总结 C++/Php/Python/Shell 程序按行读取文件或者控制台(php读取标准输入:$fp = fope ...

  9. PHP读取文件内容的五种方式(转载)

    php读取文件内容的五种方式 分享下php读取文件内容的五种方法:好吧,写完后发现文件全部没有关闭.实际应用当中,请注意关闭 fclose($fp); php读取文件内容: -----第一种方法--- ...

随机推荐

  1. 【设计模式 - 23】之模版方法模式(Template)

    1      模式简介 模版方法模式的定义: 模版方法模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中.模版方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤. 模版方法模 ...

  2. ASP.NET多线程下使用HttpContext.Current为null解决方案

    多线程或者异步调用中如何访问HttpContext? 前面我还提到在APM模式下的异步完成回调时,访问HttpContext.Current也会返回null,那么此时该怎么办呢? 答案有二种:1. 在 ...

  3. HibernateTemplate的find(String querystring)返回值具体解释

    项目源代码中出现例如以下代码: HibernateTemplate ht =-- List<Object[]> tempList = ht.find(String querystring) ...

  4. Flume NG中的Netcat Source

    NetCat是一个非常简单的Unix工具,可以读.写TCP或UDP网络连接(network connection)中数据 在Flume中的netcat支持Flume与NetCat整合,flume可以使 ...

  5. 将Java应用注册为后台服务

    项目中有一个java应用程序,交付后用户要求要把这个程序做成后台服务程序,即:系统启动后该程序可以自动启动,并且在前台不要出现运行窗口,维护人员只要在“服务管理”(Windows)中选择启动或停止即可 ...

  6. Java基础知识强化之IO流笔记25:FileInputStream / FileOutputStream 复制图片案例

    1.  需求:把D:\\美女.jpg 复制到当前项目目录下mn.jpg 代码示例: package com.himi.filecopy; import java.io.FileInputStream; ...

  7. ubuntu自定义服务模板

    根据他人代码修改: #!/bin/sh ### BEGIN INIT INFO # Provides: <pragram name> # Required-Start: $local_fs ...

  8. ReactiveCocoa 中signal(operation) then与doNext的区别

    贴源码: doNext:实现的主要源代码 return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {return [ ...

  9. Visual Studio小技巧

    换了台电脑后打开解决方案后所有项目都是展开状态,每天工作的第一件事情就是把他们都折起来,感觉好麻烦. 百度了一阵子没找到相关的问题,还一度怀疑是不是我自己的VS有问题. 但是其它解决方案没有这种情况, ...

  10. PHP 时间函数集合

    计算指定日期的前几天,几个月或者几年的函数 $a = '2014/08/21';echo date( "Y-m-d", strtotime( "-6 month  &qu ...