(オリジナル)自分で書いたツールをいくつか共有する(10)ファイルロギングツール

実際の開発では、いくつかのキーログを電話に記録する必要があります

現時点では、通常、これらのログを保存するために.txtファイルが作成されます

だから私はそのようなツールクラスを書きました

関連するログレコードを保存および表示するのに便利

具体的なコードは次のとおりです。


/**
 * Created by lenovo on 2019/10/28.
 * 日志记录工具
 */

public class FileUtil {


    //是否保存日志
    public static final boolean isLog = true;
    //存储路径
    public static final String mStrU = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zzctest.txt";

    /**
     * @param context
     * @param msg     记录信息
     */
    public static void writeMsgIntoFile(final Context context, final String msg) {
        if (context == null || isNullOrNil(msg) || isNullOrNil(mStrU) || !isLog) {
            return;
        }
        File file = new File(mStrU);
        if (!file.exists() && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            FileWriter fw = new FileWriter(mStrU, true);
            fw.write(msg + "\n");//加上换行
            fw.flush();
            fw.close();
            notifySystemToScan(context, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 得到格式化时间
     *
     * @param date
     * @param format
     * @return
     */
    public static String getFormatTime(Date date, String format) {
        if (date == null || isNullOrNil(format)) {
            return null;
        }
        SimpleDateFormat dateFormater = new SimpleDateFormat(format);
        return dateFormater.format(date);
    }

    /**
     * 扫描sd卡,进行更新
     *
     * @param context
     * @param file
     */
    public static void notifySystemToScan(Context context, File file) {
        if (context == null || file == null || !file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isNullOrNil(String str) {
        if (str == null || str.length() == 0) {
            return true;
        }
        return false;
    }
}

静的メソッドwriteMsgIntoFile()を使用する場合は、直接呼び出すだけです。

関連する読み取りおよび書き込み権限を追加することを忘れないでください。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

 

 

 

おすすめ

転載: blog.csdn.net/Android_xiong_st/article/details/102776170