android按行读取文件内容的几个方法
一、简单版
importjava.io.FileInputStream; voidreadFileOnLine(){ StringstrFileName="Filename.txt"; FileInputStreamfis=openFileInput(strFileName); StringBuffersBuffer=newStringBuffer(); DataInputStreamdataIO=newDataInputStream(fis); StringstrLine=null; while((strLine= dataIO.readLine())!=null){ sBuffer.append(strLine+“\n"); } dataIO.close(); fis.close(); }
二、简洁版
//读取文本文件中的内容 publicstaticStringReadTxtFile(StringstrFilePath) { Stringpath=strFilePath; Stringcontent="";//文件内容字符串 //打开文件 Filefile=newFile(path); //如果path是传递过来的参数,可以做一个非目录的判断 if(file.isDirectory()) { Log.d("TestFile","TheFiledoesn'tnotexist."); } else { try{ InputStreaminstream=newFileInputStream(file); if(instream!=null) { InputStreamReaderinputreader=newInputStreamReader(instream); BufferedReaderbuffreader=newBufferedReader(inputreader); Stringline; //分行读取 while((line=buffreader.readLine())!=null){ content+=line+"\n"; } instream.close(); } } catch(java.io.FileNotFoundExceptione) { Log.d("TestFile","TheFiledoesn'tnotexist."); } catch(IOExceptione) { Log.d("TestFile",e.getMessage()); } } returncontent; }
三、用于长时间使用的apk,并且有规律性的数据
1,逐行读取文件内容
//首先定义一个数据类型,用于保存读取文件的内容 classWeightRecord{ Stringtimestamp; floatweight; publicWeightRecord(Stringtimestamp,floatweight){ this.timestamp=timestamp; this.weight=weight; } } //开始读取 privateWeightRecord[]readLog()throwsException{ ArrayList<WeightRecord>result=newArrayList<WeightRecord>(); Fileroot=Environment.getExternalStorageDirectory(); if(root==null) thrownewException("externalstoragedirnotfound"); //首先找到文件 FileweightLogFile=newFile(root,WeightService.LOGFILEPATH); if(!weightLogFile.exists()) thrownewException("logfile'"+weightLogFile+"'notfound"); if(!weightLogFile.canRead()) thrownewException("logfile'"+weightLogFile+"'notreadable"); longmodtime=weightLogFile.lastModified(); if(modtime==lastRecordFileModtime) returnlastLog; //fileexists,isreadable,andisrecentlymodified--rereadit. lastRecordFileModtime=modtime; //然后将文件转化成字节流读取 FileReaderreader=newFileReader(weightLogFile); BufferedReaderin=newBufferedReader(reader); longcurrentTime=-1; //逐行读取 Stringline=in.readLine(); while(line!=null){ WeightRecordrec=parseLine(line); if(rec==null) Log.e(TAG,"couldnotparseline:'"+line+"'"); elseif(Long.parseLong(rec.timestamp)<currentTime) Log.e(TAG,"ignoring'"+line+"'sinceit'solderthanprevlogline"); else{ Log.i(TAG,"line="+rec); result.add(rec); currentTime=Long.parseLong(rec.timestamp); } line=in.readLine(); } in.close(); lastLog=(WeightRecord[])result.toArray(newWeightRecord[result.size()]); returnlastLog; } //解析每一行 privateWeightRecordparseLine(Stringline){ if(line==null) returnnull; String[]split=line.split("[;]"); if(split.length<2) returnnull; if(split[0].equals("Date")) returnnull; try{ Stringtimestamp=(split[0]); floatweight= Float.parseFloat(split[1]); returnnewWeightRecord(timestamp,weight); } catch(Exceptione){ Log.e(TAG,"Invalidformatinline'"+line+"'"); returnnull; } }
2,保存为文件
publicbooleanlogWeight(IntentbatteryChangeIntent){ Log.i(TAG,"logBattery"); if(batteryChangeIntent==null) returnfalse; try{ FileWriterout=null; if(mWeightLogFile!=null){ try{ out=newFileWriter(mWeightLogFile,true); } catch(Exceptione){} } if(out==null){ Fileroot=Environment.getExternalStorageDirectory(); if(root==null) thrownewException("externalstoragedirnotfound"); mWeightLogFile=newFile(root,WeightService.LOGFILEPATH); booleanfileExists=mWeightLogFile.exists(); if(!fileExists){ if(!mWeightLogFile.getParentFile().mkdirs()){ Toast.makeText(this,"createfilefailed",Toast.LENGTH_SHORT).show(); } mWeightLogFile.createNewFile(); } if(!mWeightLogFile.exists()){ Log.i(TAG,"out=null"); thrownewException("creationoffile'"+mWeightLogFile.toString()+"'failed"); } if(!mWeightLogFile.canWrite()) thrownewException("file'"+mWeightLogFile.toString()+"'isnotwritable"); out=newFileWriter(mWeightLogFile,true); if(!fileExists){ Stringheader=createHeadLine(); out.write(header); out.write('\n'); } } Log.i(TAG,"out!=null"); Stringextras=createBatteryInfoLine(batteryChangeIntent); out.write(extras); out.write('\n'); out.flush(); out.close(); returntrue; }catch(Exceptione){ Log.e(TAG,e.getMessage(),e); returnfalse; } }