編輯:Android 開發實例
按行讀文件看似簡單,但不同場景對性能與可維護性的要求差別很大。下面按「簡單」「簡潔」「工程化」三檔分別給出實現。
借助 DataInputStream 的 readLine() 逐行讀取,代碼最短:
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();
}
封裝成一個靜態方法,用 BufferedReader 逐行讀並拼接,同時做好異常處理:
//讀取文本文件中的內容
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;
}
如果應用會長期駐留、數據具有規律性,就需要更嚴謹的處理:定義數據結構承載每一行、加入文件修改時間的緩存判斷避免重複解析、對格式錯誤的行做容错。
先定義用於保存每行內容的數據類型:
//首先定義一個數據類型,用於保存讀取文件的內容
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;
}
}
寫入側同樣需要兼顧健壯性:先嘗試複用已有文件對象,失敗則回退到外部存儲;首次創建時自動建立父目錄並寫入表頭;每一步都檢查文件是否存在、可讀可寫,任何異常都記錄日誌而非直接崩潰。
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;
}
}
三種寫法的取捨很清晰:一次性小文件用第一種即可;常規業務邏輯用第二種;而需要長期運行、頻繁讀寫的場景,第三種的緩存判斷與容错設計能顯著降低崩潰風險與不必要的 I/O。
Android K 的偽沉浸式狀態欄實作
背景 Android 5.0 之後,狀態欄沉浸式可透過 setStatusBarColor 等 API 完成。Android 4.4 沒有完整 API,但可以透過透明狀態
Android 錄音功能實作:以 MediaRecorder 做按住說話
本文示範如何實作一個類似微信「按住說話」的錄音功能:手指按下開始錄音,放開停止,音檔自動存到 SD 卡。 版面配置 <LinearLayout xmlns:and
Android 五種資料儲存方式全解析:SharedPreferences、檔案、SQLite、ContentProvider 與網路
資料儲存是開發中最頻繁面對的課題之一。Android 提供了多種互補的機制,本文逐一說明五種主要方式,並附上各自的關鍵程式碼與適用情境。 SharedPreferen
Android 載入 Spinner 進度指示實作
在 Android 裡,當某項工作正在進行、想讓使用者知道「系統還在忙」,就可以用進度條來表達。進度條大致有兩種形式:帶有進度的水平進度列,以及持續旋轉的載入轉圈(Spi