Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;

import java.util.Calendar;

import android.util.Log;

public class Main {
    private static String m_strTag = null;
    private static String m_strLogFilePath = "";
    private static String m_strLogFileName = "logs.txt";
    private static boolean m_boolWrite = false;

    public static void e(String strFormat, Object... args) {
        if ((strFormat == null) || (strFormat.length() == 0))
            return;

        String strMessage = strFormat;
        if (args.length != 0)
            strMessage = String.format(strFormat, args);

        int nLine = Thread.currentThread().getStackTrace()[3].getLineNumber();
        String strClass = Thread.currentThread().getStackTrace()[3].getClassName();
        String strMethod = Thread.currentThread().getStackTrace()[3].getMethodName();
        strClass = strClass.substring(strClass.lastIndexOf(".") + 1);

        String str = String.format("[%5d] %-50s %s", nLine, strClass + ":" + strMethod, strMessage);
        Log.e(m_strTag, str);
        write("[E]", m_strTag, str);
    }

    private static void write(String strLevel, String strTag, String strMessage, Object... args) {
        if (!m_boolWrite)
            return;

        String _strMessage = strMessage;
        if ((strMessage == null) || (strMessage.length() == 0))
            return;

        if (args.length != 0)
            _strMessage = String.format(strMessage, args);

        _strMessage = strLevel + " " + getCurrentTime() + "\t" + strTag + "\t" + _strMessage + "\n";

        File file = new File(m_strLogFilePath + "/" + m_strLogFileName);
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file, true);
            if (fos != null)
                fos.write(_strMessage.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        String strTime = String.format("%4d-%02d-%02d %02d:%02d:%02d", calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        return strTime;
    }
}