2

我使用了一个初始化记录器和参数的函数。虽然我在控制台中调用了这个函数 LogMsg 和换行符,但它在文本文件中只给出了一行。为什么呢?

String logmsg="Line1\n"+"Line2\n";

public static void LogMsg(Logger logger,String pathname,Level level,String logmsg){
    //logger=Logger.getLogger("LogMsg");
    FileHandler fh=null;
    try {
        fh = new FileHandler(pathname,300000,1,true);
        fh.setFormatter(new SimpleFormatter());
         LogRecord record1 = new LogRecord(level, logmsg);
         logger.addHandler(fh);
            logger.log(record1);
            fh.close();

    } catch (SecurityException e) {
        // TODO Auto-generated catch block

        //e.printStackTrace();
        System.out.println("Failed to log message due to lack of permissions.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();

        System.out.println("Failed to log message");
    }


}
4

1 回答 1

2

尝试

String logmsg="Line1\r\n"+"Line2\r\n";

或者更好

logmsg = String.Concat("Line1",Environment.NewLine,"Line2",Environment.NewLine);

或者最好还是使用 StringBuilder 之类的东西

logmsg = CreateLogMessage(new string [] {"Line1", "Line2"});

public static CreateLogMessage(string[] argLines);
{
  StringBuilder sb = new StringBuilder(argLines.Length);
  foreach(String line in argLines)
  {
    sb.AppendLine(line);
  }
  return sb.ToString();
}

Environment.Newline 将根据预期的行尾标记来处理操作系统差异。

于 2012-10-25T13:49:42.413 回答