/**
* @author zuo
* @date 2018/6/20 12:37
*/
public class LogUtil {
private static final String FILE_NAME = "/logs.txt";
private static Boolean MYLOG_SWITCH = true; // 日志文件总开关
public static void i(String str) {
if (MYLOG_SWITCH) {
writeException(str);
}
}
public static void LogException(Exception e) {
if (MYLOG_SWITCH) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String str = sw.toString();
writeException(str);
} else {
e.printStackTrace();
}
}
private static void writeException(String content) {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获取SD卡的目录
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile = new File(sdCardDir.getCanonicalPath()
+ FILE_NAME);
@SuppressLint("SimpleDateFormat")
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
String logStr = String.format("\n\n%s\n%s", date, content);
// 以指定文件创建RandomAccessFile对象
RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
// 将文件记录指针移动到最后
raf.seek(targetFile.length());
// 输出文件内容
raf.write(logStr.getBytes());
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readException() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 获得SD卡对应的存储目录
File sdCardDir = Environment.getExternalStorageDirectory();
// 获取指定文件对应的输入流
FileInputStream fis = new FileInputStream(
sdCardDir.getCanonicalPath() + FILE_NAME);
// 将指定输入流包装成BufferReader
BufferedReader br = new BufferedReader(new InputStreamReader(
fis));
StringBuilder sb = new StringBuilder("");
String line = null;
// 循环读取文件内容
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
网友评论