JAVA生成TXT日志文件

时间:2023-01-28 17:23:03
技术交流群:233513714



1
/** 2 * 生成日志文件(文件的位置在Tomcat的安装路径下) 3 * @param str 4 */ 5 public static void LogForTXT(String str) { 6   try { 7     String dir = System.getProperty("user.dir") + File.separator + "系统日志"; 8     File fi = new File(dir); 9     if (!fi.exists()) { 10       fi.mkdirs(); 11     } 12     Date date = new Date(); 13     String time = new SimpleDateFormat("yyyy-MM-dd").format(date); 14     dir = fi.getPath() + File.separator + time + ".txt"; 15     fi = new File(dir); 16     if (!fi.exists() && !fi.isDirectory()) { 17       fi.createNewFile(); 18       PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fi))); 19       pw.println(" " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "生成日志文件"); 20       pw.println("-----------------------------日志-----------------------------"); 21       pw.println(str); 22       pw.close(); 23     } else { 24       PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fi, true))); 25       pw.println(str); 26       pw.close(); 27     } 28   } catch (Exception e) { 29     e.printStackTrace(); 30   } 31 }