package main; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; // ÐÞ¸´£ºÊ¹Óà java.util.Date ¶ø²»ÊÇ java.sql.Date import java.text.SimpleDateFormat; /** * ÈÕÖ¾¼Ç¼¹¤¾ßÀà */ public class LogUtil { private static final String LOG_DIR = "systemfile/logfile"; private static final String LOG_FILE = LOG_DIR + "/openlog.txt"; private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * ¼Ç¼³ÌÐòÆô¶¯ÈÕÖ¾ */ public static void logOpen() { ensureLogDirExists(); String timestamp = DATE_FORMAT.format(new Date()); writeLog("³ÌÐòÆô¶¯: " + timestamp + "\n"); } /** * ¼Ç¼³ÌÐò¹Ø±ÕÈÕÖ¾²¢¼ÆË㹤×÷ʱ³¤ * @param startTime ³ÌÐòÆô¶¯Ê±¼ä´Á */ public static void logClose(long startTime) { ensureLogDirExists(); long endTime = System.currentTimeMillis(); String closeTime = DATE_FORMAT.format(new Date(endTime)); // ¼ÆË㹤×÷ʱ³¤ long duration = endTime - startTime; String durationStr = formatDuration(duration); String log = "³ÌÐò¹Ø±Õ: " + closeTime + "\n" + "¹¤×÷ʱ³¤: " + durationStr + "\n" + "-----------------------------------\n"; writeLog(log); } /** * È·±£ÈÕ־Ŀ¼´æÔÚ */ private static void ensureLogDirExists() { File dir = new File(LOG_DIR); if (!dir.exists()) { boolean created = dir.mkdirs(); // ´´½¨¶à¼¶Ä¿Â¼ if (!created) { System.err.println("ÎÞ·¨´´½¨ÈÕ־Ŀ¼: " + LOG_DIR); } } } /** * ¸ñʽ»¯Ê±³¤£¨ºÁÃë¡ú¿É¶Á×Ö·û´®£© */ private static String formatDuration(long millis) { long seconds = millis / 1000; long hours = seconds / 3600; long minutes = (seconds % 3600) / 60; seconds = seconds % 60; return String.format("%dСʱ %d·ÖÖÓ %dÃë", hours, minutes, seconds); } /** * дÈëÈÕÖ¾µ½Îļþ£¨×·¼Óģʽ£© */ private static void writeLog(String content) { try (FileWriter fw = new FileWriter(LOG_FILE, true); BufferedWriter bw = new BufferedWriter(fw)) { bw.write(content); bw.flush(); // È·±£ÄÚÈÝÁ¢¼´Ð´Èë } catch (IOException e) { System.err.println("дÈëÈÕ־ʧ°Ü: " + e.getMessage()); } } }