文件讀寫

public class ShowLog extends Activity {
// log文件     sdcard/agingtest/AgingtestLog.txt
    private static String LOGFILENAME = "AgingtestLog.txt";
    private static String LOGFILEPATH = Environment
            .getExternalStorageDirectory() + "/agingtest";
    private static SimpleDateFormat LogSdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss.SSS");
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_log);

        TextView tvLog = (TextView) findViewById(R.id.tv_log);
        tvLog.setMovementMethod(ScrollingMovementMethod.getInstance());

        StringBuffer sb = new StringBuffer();

        File file = new File(LOGFILEPATH, LOGFILENAME);
//讀
        try {
            FileInputStream fr = new FileInputStream(file);//文件輸出流
            BufferedReader br = new BufferedReader(new InputStreamReader(fr, "utf-8"));//緩衝讀取文件數據
            String line = "" ;//記錄每一行數據
            String content = "" ;
            while((line = br.readLine()) != null){//如果還有下一行數據
                content += line + "\n" ;
            }
            Log.i("wqtest","log11:" + content);
            tvLog.setText(content);//追加顯示數據
            br.close();//關閉文件輸出流
            fr.close();//關閉緩衝區
        } catch (IOException e) {//拋出異常
            Toast.makeText(this, "沒有此文件!", Toast.LENGTH_SHORT).show();//提示異常
            finish();//直接關閉界面
        }

    }

//寫

writeLog("error", tag, text);

private static void writeLog(String mylogtype, String tag, String text) {
   FileOutputStream fos = null;
   try {
      File logFile = new File(LOGFILEPATH, LOGFILENAME);
      File fileDir = logFile.getParentFile();
      if ((fileDir != null) && (!fileDir.exists())) {
         fileDir.mkdirs();
      }

      if ((logFile != null) && logFile.exists()) {
         if (fileSize > 300 * 1024 * 1024) {// delete if > 300M
            boolean delResult = logFile.delete();
         }
      }

      fos = new FileOutputStream(logFile, true);
      Date nowtime = new Date();
      String needWriteMessage = LogSdf.format(nowtime) + "-" + mylogtype
            + "-" + tag + ": ---" + text + "\n";
      if (needWriteMessage != null) {
         fos.write(needWriteMessage.getBytes());
         fos.flush();
      }
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      try {
         if (fos != null) {
            fos.close();
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

}


發佈了40 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章