【android应用】本地日志功能开发--获取文件最后时间

添加本地日志功能,将日志写入到文件。避免关键日志丢失。更好的查看log,定位问题。

一、基本思路

1、写文件

2、当文件到一定大小时,更名为其他文件

3、根据创建时间选择要更名文件

4、rename

二、根据时间选择更名文件

使用 File类 lastModified 方法 获取最后修改时间。

注意:没有文件时会返回 0.

    /**
     * 获取保存文件
     *
     * @return
     */
    private File getSaveFile() {
        File file = null;
        File saveFile = null;
        try {
            for(int i =0; i <= mMaxCount; i++){
                String filename = String.format(LOG_FILE_NAME_N, i);
                file = new File(mContext.getFilesDir(), filename);
                long time = file.lastModified();
                if(time == 0){
                    return file;
                }

                if(saveFile == null){
                    saveFile = file;
                    continue;
                }

                if(time < saveFile.lastModified()){
                    saveFile = file;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getSaveFileName: error " + e.toString());
            saveFile = new File(mContext.getFilesDir(), String.format(LOG_FILE_NAME_N, 0));
            return saveFile;
        }

        return saveFile;
    }

三、更名文件

使用 File类 renameTo 方法更名文件。

    /**
     * 保存log文件
     *
     * @return 返回
     */
    private void saveLogfile() {
        try {
            File logfile = new File(mContext.getFilesDir(), LOG_FILE_NAME);
            if (logfile.length() < getLength()) {
                return;
            }

            long localTime = new Date().getTime();
            File savefile = getSaveFile();
            if(localTime >= savefile.lastModified()){
                closeLogFile();
                savefile.delete();
                logfile.renameTo(savefile);
            }
        } catch (Exception e) {
            Log.d(TAG, "getFime: error " + e.toString());
        }
        return;
    }

四、java源码

package com.android.vpsc.publicapi;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

public class WriteLogToFile {
    private static final String TAG = "WriteLogToFile";
    private static WriteLogToFile mWriteLogToFile = null;
    private Context mContext = null;

    private static final String LOG_FILE_NAME = "logger.txt";
    private static final String LOG_FILE_NAME_N = "logger_%d.txt";
    private static final int mMaxCount = 3;

    private static final int KB = 1024;
    private static final int MB = 1024 * KB;
    private static final int LOG_FILE_MAX_LENGTH = 10 * MB;
    private OutputStream outputStream = null;

    private WriteLogToFile(Context context) {
        if (mContext == null) {
            mContext = context;
        }
    }

    public static synchronized WriteLogToFile getInstance(Context context) {
        if (mWriteLogToFile == null) {
            mWriteLogToFile = new WriteLogToFile(context);
        }

        return mWriteLogToFile;
    }

    /**
     * 获取配置文件大小
     *
     * @return
     */
    private long getLength() {
        return LOG_FILE_MAX_LENGTH;
    }

    /**
     * 获取保存文件
     *
     * @return
     */
    private File getSaveFile() {
        File file = null;
        File saveFile = null;
        try {
            for(int i =0; i <= mMaxCount; i++){
                String filename = String.format(LOG_FILE_NAME_N, i);
                file = new File(mContext.getFilesDir(), filename);
                long time = file.lastModified();
                if(time == 0){
                    return file;
                }

                if(saveFile == null){
                    saveFile = file;
                    continue;
                }

                if(time < saveFile.lastModified()){
                    saveFile = file;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getSaveFileName: error " + e.toString());
            saveFile = new File(mContext.getFilesDir(), String.format(LOG_FILE_NAME_N, 0));
            return saveFile;
        }

        return saveFile;
    }

    /**
     * 保存log文件
     *
     * @return 返回
     */
    private void saveLogfile() {
        try {
            File logfile = new File(mContext.getFilesDir(), LOG_FILE_NAME);
            if (logfile.length() < getLength()) {
                return;
            }

            long localTime = new Date().getTime();
            File savefile = getSaveFile();
            if(localTime >= savefile.lastModified()){
                closeLogFile();
                savefile.delete();
                logfile.renameTo(savefile);
            }
        } catch (Exception e) {
            Log.d(TAG, "getFime: error " + e.toString());
        }
        return;
    }

    /**
     * 打开文件
     */
    private void openLogfile() {
        try {
            if (outputStream == null) {
                File logFile = new File(mContext.getFilesDir(), LOG_FILE_NAME);
                outputStream = new FileOutputStream(logFile, true);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭文件
     */
    private void closeLogFile() {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
                outputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写log文件
     *
     * @param log log 内容
     */
    public void writeLog(String log) {
        if (StringUtils.isNullOrEmpty(log)) {
            return;
        }
        try {
            saveLogfile();
            if (outputStream == null) {
                openLogfile();
            }
            outputStream.write(log.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
发布了61 篇原创文章 · 获赞 45 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/twk121109281/article/details/103298219