android按行讀取文件內(nèi)容的幾個(gè)方法
一、簡(jiǎn)單版
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();
}
二、簡(jiǎn)潔版
//讀取文本文件中的內(nèi)容
public static String ReadTxtFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件內(nèi)容字符串
//打開(kāi)文件
File file = new File(path);
//如果path是傳遞過(guò)來(lái)的參數(shù),可以做一個(gè)非目錄的判斷
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;
}
三、用于長(zhǎng)時(shí)間使用的apk,并且有規(guī)律性的數(shù)據(jù)
1,逐行讀取文件內(nèi)容
//首先定義一個(gè)數(shù)據(jù)類(lèi)型,用于保存讀取文件的內(nèi)容
class WeightRecord {
String timestamp;
float weight;
public WeightRecord(String timestamp, float weight) {
this.timestamp = timestamp;
this.weight = weight;
}
}
//開(kāi)始讀取
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;
// 然后將文件轉(zhuǎn)化成字節(jié)流讀取
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;
}
}
相關(guān)文章
使用Win10+Android+夜神安卓模擬器,搭建ReactNative開(kāi)發(fā)環(huán)境
今天小編就為大家分享一篇關(guān)于使用Win10+Android+夜神安卓模擬器,搭建ReactNative開(kāi)發(fā)環(huán)境,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10
Android自定義View實(shí)現(xiàn)跟隨手指移動(dòng)的小兔子
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)跟隨手指移動(dòng)的小兔子,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
Android 中的危險(xiǎn)權(quán)限詳細(xì)整理
這篇文章主要介紹了Android 中的危險(xiǎn)權(quán)限詳細(xì)整理的相關(guān)資料,Android 中有上百種權(quán)限,現(xiàn)在將所有的權(quán)限歸為兩類(lèi),一類(lèi)是普通權(quán)限,一類(lèi)的危險(xiǎn)權(quán)限,危險(xiǎn)權(quán)限則表示那些可能會(huì)觸及到用戶(hù)安全隱私或者對(duì)設(shè)備安全造成影響的權(quán)限,需要的朋友可以參考下2017-07-07
Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解
這篇文章主要為大家介紹了Flutter?Widget?之StatefulBuilder構(gòu)建方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
實(shí)例講解Android中ViewPager組件的一些進(jìn)階使用技巧
這篇文章主要介紹了Android中ViewPager組件的一些進(jìn)階使用技巧,包括添加標(biāo)題與onPagerChangeListener監(jiān)聽(tīng)使用等,需要的朋友可以參考下2016-03-03
Android重寫(xiě)TextView實(shí)現(xiàn)文字整齊排版的方法(附demo源碼下載)
這篇文章主要介紹了Android重寫(xiě)TextView實(shí)現(xiàn)文字整齊排版的方法,結(jié)合實(shí)例形式分析了Android重寫(xiě)TextView實(shí)現(xiàn)文字整齊排版的相關(guān)技巧,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2016-02-02
Android布局控件View?ViewRootImpl?WindowManagerService關(guān)系
這篇文章主要為大家介紹了Android布局控件View?ViewRootImpl?WindowManagerService關(guān)系示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Android虛擬導(dǎo)航欄遮擋底部的輸入框的解決方法
下面小編就為大家分享一篇Android虛擬導(dǎo)航欄遮擋底部的輸入框的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Android13實(shí)時(shí)刷新頻率的實(shí)現(xiàn)代碼(完整代碼)
文章介紹了Android 13中如何通過(guò)設(shè)置開(kāi)發(fā)者選項(xiàng)顯示屏幕刷新頻率,具體涉及到Settings應(yīng)用中的代碼和SurfaceFlinger服務(wù)的實(shí)現(xiàn),感興趣的朋友一起看看吧2025-01-01

