zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JAVA文件异常 示例 信息 txt 存入 捕获
2023-06-13 09:15:24 时间

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

复制代码代码如下:


packagehelpEntity;

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.PrintWriter;
importjava.text.SimpleDateFormat;
importjava.util.Date;

publicclassLog{
 privateFilefile=null;

 publicFilegetFile(){
  returnfile;
 }

 publicvoidsetFile(Filefile){
  this.file=file;
 }

 publicvoidsaveLog(Exceptione,StringyouName){
  try{
   StringnowPath=null;
   nowPath=System.getProperty("user.dir");
   StringtempPath=null;
   this.file=newFile(nowPath);
   tempPath=this.file.getParent();
   if(tempPath==null){
    this.file=newFile(nowPath);
   }
   this.file=newFile(tempPath+""+File.separator+"log.txt");
   PrintWriterwriter=null;
   FileWriterfileWrite=newFileWriter(file,true);
   writer=newPrintWriter(fileWrite);
   writer.append(System.getProperty("line.separator")
     +newSimpleDateFormat("yyyy-MM-dd:HH:mm:ss")
       .format(newDate())+"__"+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(Exceptione2){
   e2.printStackTrace();
  }
 }
}