一、简单版

 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. Lottery - CodeForces 589I(水)

    题目大意:有N个球K个人,现在要给这N个球涂上K种颜色,要求使抽到球的不同颜色的概率一致(N确保是K的倍数),求出来至少要给多少个球重新涂上颜色. 分析:先求出来所有球的每种颜色的个数,然后不到平均数 ...

  2. oc学习之路-----搞死指针之内存存储int类型

    关于每个数据类型个字节在内存中的存储地址(以int为例) 先上图 如题,为什么说好的*p = &c是1啊,为什么是513呢,一开始,我也觉得挺惊讶的,后面听老师分析了一下才知道怎么回事,但是还 ...

  3. xutils Error:(37, 39) 错误: 无法访问HttpRequestBase 找不到org.apache.http.client.methods.HttpRequestBase的类文件

    Android 6.0(api 23)SDK已经强制移除httpclient 解决方案: 1降低api 2build.gradle中添加一句话 android { useLibrary'org.apa ...

  4. Theano FCN实现与训练经验与教训小结

    NaN 计算softmax loss时要用numeric robust 的计算方式. softmax与 loss可能要分开计算. 得到前者的计算方式可以是常规方法. 但计算后者时要注意无穷大和NaN的 ...

  5. ASP.NET MVC- Controllers and Routing- Routing

    二.Creating Custom Routes In this tutorial, you learn how to  add a custom route to an ASP.NET MVC ap ...

  6. Winform DataTable 客户端操作数据

    //创建 DataTable DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add(" ...

  7. bootstrap学习笔记--bootstrap网格系统

    移动设备优先 移动设备优先是 Bootstrap 3 的最显著的变化. 在之前的 Bootstrap 版本中(直到 2.x),您需要手动引用另一个 CSS,才能让整个项目友好的支持移动设备. 现在不一 ...

  8. msvcp110.dll丢失

    方法1:建议下载并安装[百度电脑专家],在搜索框内输入“vs2012运行时库缺失”,在搜索结果里面选择[立即修复],修复完成后验证是否正常: 方法2:手动修复 2.1 在[百度]下载“msvcp110 ...

  9. leetcode 题解 || Swap Nodes in Pairs 问题

    problem: Given a linked list, swap every two adjacent nodes and return its head. For example, Given ...

  10. [Webpack 2] Grouping vendor files with the Webpack CommonsChunkPlugin

    Often, you have dependencies which you rarely change. In these cases, you can leverage the CommonsCh ...