我是靠谱客的博主 大意含羞草,最近开发中收集的这篇文章主要介绍Android 开发技巧之Log写入文件,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在Android开发的时候经常会遇到手机offline,影响日志的查看与分析。为此,我写了一个简单的类用于将日志写入文件中,便于以后调试的时候可以拿来使用:

package org.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogWriter {
	
	private static LogWriter mLogWriter;

	private static String mPath;
	
	private static Writer mWriter;
	
	private static SimpleDateFormat df;
	
	private LogWriter(String file_path) {
		this.mPath = file_path;
		this.mWriter = null;
	}
	
	public static LogWriter open(String file_path) throws IOException {
		if (mLogWriter == null) {
			mLogWriter = new LogWriter(file_path);
		}
		File mFile = new File(mPath);
		mWriter = new BufferedWriter(new FileWriter(mPath), 2048);
		df = new SimpleDateFormat("[yy-MM-dd hh:mm:ss]: ");
		
		return mLogWriter;
	}
	
	public void close() throws IOException {
		mWriter.close();
	}
	
	public void print(String log) throws IOException {
		mWriter.write(df.format(new Date()));
		mWriter.write(log);
		mWriter.write("n");
		mWriter.flush();
	}
	
	public void print(Class cls, String log) throws IOException { //如果还想看是在哪个类里可以用这个方法
		mWriter.write(df.format(new Date()));
		mWriter.write(cls.getSimpleName() + " ");
		mWriter.write(log);
		mWriter.write("n");
		mWriter.flush();
	}
	
}
感觉在整个程序中进行写日志操作之后用到一个实例,所以我用了单例模式


使用这个类的代码:

	private LogWriter mLogWriter;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        
        File logf = new File(Environment.getExternalStorageDirectory()
        		+ File.separator + "DemoLog.txt");
        
        try {
			mLogWriter = LogWriter.open(logf.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(tag, e.getMessage());
		}
        
        log("onCreate()");
    }
    
    public void log(String msg) {
    	Log.d(tag, msg);
    	
    	try {
			mLogWriter.print(AlarmManagerDemo.class, msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(tag, e.getMessage());
		}
    }



最后

以上就是大意含羞草为你收集整理的Android 开发技巧之Log写入文件的全部内容,希望文章能够帮你解决Android 开发技巧之Log写入文件所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部