一、简单版

 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. Shell脚本高级应用 --实现远程MySQL自动查询[转

    #!/bin/sh Host=192.168.5.30 User=abccdef PW=123456 MSG=`mysql -h$Host -u$User -p$PW <<EOF show ...

  2. 国外NET 空间免费申请使用

    最近研究微信公众帐号接口开发,需要使用到域名和空间,所以在度娘和谷哥的帮助下找到国外免费的空间, 刚刚注册完所以截图和大家分享下 注册地址:http://member.mywindowshosting ...

  3. 数位DP问题整理(一)

    第一题:Amount of degrees (ural 1057) 题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1057 题意:[x,y ...

  4. 探索WebKit内核(一)------ 菜鸟起步

    为什么搞WebKit 如今研究WebKit的人越来越多,俺不能免俗,也增加当中.WebKit的火爆也是得益于浏览器和WebOS的混战,随着Palm WebOS, Chrome OS, Firefox ...

  5. 关闭对话框,OnClose和OnCancel

    我们知道,在对话框中,屏蔽ESC键自己主动退出能够选择重载OnCancel为哑函数的方法: void CXXXXDlg::OnCancel()      {         // TODO: Add ...

  6. ios6如何处理内存,分别为前警告后

    这里有一篇文章.非常具体地说明了ios6前后是怎样处理内存警告的: 来自唐巧的技术博客:http://blog.devtang.com/blog/2013/05/18/goodbye-viewdidu ...

  7. Swift 实现图片转字符画的功能

    本文介绍一个IOS APP , 将图片转换成ASCII字符画,使用Swift语言编写. 举个例子,我们使用著名的蕾娜照片作为原图片 经APP转换后形成的字符画,我们打印出来,效果如下: 放大她的脸部可 ...

  8. 【转】正确使用Block避免Cycle Retain和Crash

    原文地址:http://tanqisen.github.io/blog/2013/04/19/gcd-block-cycle-retain/ 使用指南:http://blog.csdn.net/nic ...

  9. CocoaPods导入第三方库头文件自动补齐

    使用了一段时间CocoaPods来管理Objective-c的类库,方便了不少.但是有一个小问题,当我在xcode输入import关键字的时候,没有自动联想补齐代码的功能,需要手工敲全了文件名,难以适 ...

  10. linux中的帮助命令 分类: linux 学习笔记 ubuntu 2015-07-05 19:07 31人阅读 评论(0) 收藏

    说实话,到目前为止我还是不太习惯使用linux自带的帮助文档,遇到问题都是去查我自己下载的chm格式的命令大全,不过这些帮助命令我们还是有必要了解的. 1.man [要查看的命令名称] 例如想要查看l ...