Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 按行讀取文件內容的幾種實現方式

編輯: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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved