android按行读取文件内容的几个方法
程序员文章站
2023-02-02 12:42:56
一、简单版
复制代码 代码如下:
import java.io.fileinputstream;
void readfileonline(){
st...
一、简单版
复制代码 代码如下:
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;
}
}