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); //打开文件 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按行读取文件内容的几个方法的更多相关文章
- Python跳过第一行读取文件内容
Python编程时,经常需要跳过第一行读取文件内容.比较容易想到是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作.相应的Python代码如下: inpu ...
- php中读取文件内容的几种方法。(file_get_contents:将文件内容读入一个字符串)
php中读取文件内容的几种方法.(file_get_contents:将文件内容读入一个字符串) 一.总结 php中读取文件内容的几种方法(file_get_contents:将文件内容读入一个字符串 ...
- 【Shell】按行读取文件内容
方法1:while循环中执行效率最高,最常用的方法. function while_read_LINE_bottm(){ While read LINE do echo $LINE done < ...
- php中读取文件内容的几种方法
1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件中读取最多 length 个字节.该函数在读取完最多 ...
- php读取文件内容的三种方法
<?php //**************第一种读取方式***************************** 代码如下: header("content-type:text/h ...
- [转]Python跳过第一行读取文件内容
from itertools import islice file_name='XXXX' input_file = open(file_name) for line in islice(input_ ...
- C++/Php/Python/Shell 程序按行读取文件或者控制台
写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下.方便使用 1. C++ 读取文件 #include<stdio.h> #include<string.h> i ...
- C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。
C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结. 一.总结 C++/Php/Python/Shell 程序按行读取文件或者控制台(php读取标准输入:$fp = fope ...
- PHP读取文件内容的五种方式(转载)
php读取文件内容的五种方式 分享下php读取文件内容的五种方法:好吧,写完后发现文件全部没有关闭.实际应用当中,请注意关闭 fclose($fp); php读取文件内容: -----第一种方法--- ...
随机推荐
- POJ 1113 Wall 凸包求周长
Wall Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 26286 Accepted: 8760 Description ...
- MINA学习之IoService
从上一篇文章中知道,IoService出于MINA体系中的底层.IoService将会帮你维护网络交互,接受消息,发送消息,管理Sessions,管理连接Connections等等. IoServic ...
- Winform DataTable 客户端操作数据
//创建 DataTable DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add(" ...
- 解决拦截器对ajax请求的的拦截
拦截器配置: public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object obj) ...
- 20169210《Linux内核原理与分析》第九周作业
第一部分:实验 首先还是网易云课堂的学习,这次的课程是可执行程序的装载. 预处理.编译和链接: 可执行程序是怎么来的 以c语言代码为例的话,经过预处理,编译成汇编代码,再汇编成目标码再链接可执行文件. ...
- centos7 搭建 docker 环境
1. 安装centos7 http://isoredirect.centos.org/centos/7/isos/x86_64/ 下载 everything 版本,最小化版本可能缺失很多东西 我是在 ...
- adt-bundle-linux-x86_64-20131030下新建project提示找不到adb和R.java问题的解决
adt-bundle-linux-x86_64-20131030下新建project提示找不到adb和R.java问题的解决 在ubuntu14.04下,搭建Android开发环境,下载官方的adt- ...
- XC文件管理器(Android应用)
XC文件管理器,是基于Android4.4开发的一个方便易用的文件管理器,具有文件的目录管理和文件的管理,主要包括文件的新建.删除.重命名.复制,移动剪切以及文件详情查看等文件和目录的功能,同时支持文 ...
- VC++中 wstring和string的互相转换实现
在VC++开发中,经常会用到string和wstring,这就需要二者之间的转换,项目中封装了wstring和string相互转换的2个函数,实现如下: //将wstring转换成string std ...
- "ORA-00942: 表或视图不存在 "的原因和解决方法
"ORA-00942: 表或视图不存在 "的原因和解决方法 采用Oracle数据库,使用Powerdesigner设计,生成Sql文件导入后查询出现“ORA-00942: 表或 ...