我使用了一个初始化logger和参数的函数。 虽然我在控制台中调用了这个函数LogMsg和newline,但它在文本文件中给出了一行。为什么会这样?
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");
}
}
答案 0 :(得分:2)
尝试
String logmsg="Line1\r\n"+"Line2\r\n";
或更好
logmsg = String.Concat("Line1",Environment.NewLine,"Line2",Environment.NewLine);
或者更好的是仍然使用类似
的StringBuilderlogmsg = 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将根据预期的行尾令牌来处理os差异。