欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java捕获异常信息存入txt文件示例

程序员文章站 2024-02-26 08:00:27
捕获程序中出现的异常 可用于后期维护的必要性!做简单的测试 ! 复制代码 代码如下:package helpentity; import java.io.buffere...

捕获程序中出现的异常 可用于后期维护的必要性!做简单的测试 !

复制代码 代码如下:

package helpentity;

import java.io.bufferedreader;
import java.io.file;
import java.io.filereader;
import java.io.filewriter;
import java.io.printwriter;
import java.text.simpledateformat;
import java.util.date;

public class log {
 private file file = null;

 public file getfile() {
  return file;
 }

 public void setfile(file file) {
  this.file = file;
 }

 public void savelog(exception e, string youname) {
  try {
   string nowpath = null;
   nowpath = system.getproperty("user.dir");
   string temppath = null;
   this.file = new file(nowpath);
   temppath = this.file.getparent();
   if (temppath == null) {
    this.file = new file(nowpath);
   }
   this.file = new file(temppath + "" + file.separator + "log.txt");
   printwriter writer = null;
   filewriter filewrite = new filewriter(file, true);
   writer = new printwriter(filewrite);
   writer.append(system.getproperty("line.separator")
     + new simpledateformat("yyyy-mm-dd:hh:mm:ss")
       .format(new date()) + "__" + youname);
   writer.append(system.getproperty("line.separator"));
   writer.append("      *************************" + e.tostring()
     + "*************************");
   writer.append(system.getproperty("line.separator"));
   e.printstacktrace(writer);
   writer.flush();
   writer.close();
  } catch (exception e2) {
   e2.printstacktrace();
  }
 }
}