2015-04-22 57 views
-1

我想執行日誌記錄。我創建了一個類,但是這個類不創建一個文件。登錄Java,未創建文件

此類爲記錄:

public class Log { 
private static File logFile = new File("log.txt"); 
public Log() { 
    if (!logFile.exists()) { 
     try { 
      logFile.createNewFile(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

public static void write(String msg) { 
    writeInFile(createString(msg)); 
} 

private static String createString(String msg) { 
    StringBuilder sb = new StringBuilder(100); 
    sb.append(MyDate.currentDate()).append("\t| ").append(msg); 
    return sb.append('\n').toString(); 
} 

private static void writeInFile(String msg) { 
    try (BufferedWriter out = new BufferedWriter(new FileWriter(logFile, 
      true))) { 
     out.write(msg); 
     out.flush(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

static class MyDate { 
    public static String currentDate() { 
     DateFormat formatter = new SimpleDateFormat("HH:mm.ss"); 
     Date date = new Date(); 
     return formatter.format(date); 
    } 
}} 

我在diferent方法

+3

爲什麼你要自己實現而不是僅僅使用日誌庫,比如logback? –

+0

您是否收到任何錯誤?另外,你確定你正在尋找正確的文件夾中的文件? –

+0

我在我的項目文件夾中搜索,但找不到filr log.txt( – Lev

回答

1

添加Log.write("some text for log");檢查該文件的canonical path位置。您擁有的代碼取決於當前的工作目錄。