gpt4 book ai didi

java - 使用 SimpleFormatter 限制字符串长度

转载 作者:行者123 更新时间:2023-11-30 08:40:18 24 4
gpt4 key购买 nike

我试图以 SimpleFormatter 格式限制源参数的长度,以便在 Tomcat 8 中使用。

我读过 SimpleFormatter docFormatter syntax doc虽然我不会假装我已经理解了第二个,但在参数后面跟一个数字应该会限制它的长度。

但它不在我的测试中:

输出的行

java.util.logging.SimpleFormatter.format = %4$s %n

java.util.logging.SimpleFormatter.format =%4$1s %n

无法区分。

我错过了什么吗?

最佳答案

I'm trying to limit the length of the source parameter in a SimpleFormatter format, to use in Tomcat 8.

由于您只需要关卡的第一个字符,因此语法为 %4$.1s

根据 java.util.Formatter JavaDocs :

The format specifiers for general, character, and numeric types have the following syntax:

   %[argument_index$][flags][width][.precision]conversion

The optional width is a positive decimal integer indicating the minimum number of characters to be written to the output.

The optional precision is a non-negative decimal integer usually used to restrict the number of characters.

这意味着使用点字符指定精度。由于您不关心最大值如果最小值为零,那么您必须从模式中省略它。

这是一个构建模式的示例测试用例:

public static void main(String[] args) {
//This really should be set as a command argument but, it works.

//No min and max of seven chars of level.
//System.setProperty("java.util.logging.SimpleFormatter.format", "%4$.7s %n");

//Min and max of seven chars of level (right justified).
//System.setProperty("java.util.logging.SimpleFormatter.format", "%4$7.7s %n");

//Min and max of seven chars of level (left justified).
//System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7.7s %n");

//No min with max of one chars of level.
System.setProperty("java.util.logging.SimpleFormatter.format", "%4$.1s %n");

LogRecord r = new LogRecord(Level.SEVERE, "Message");
r.setLoggerName("logger");
r.setSourceClassName("class");
r.setSourceMethodName("method");
System.out.println(new SimpleFormatter().format(r));
}

JavaDocs 还声明:

For character, integral, and date/time argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.

文档实际上应该说“参数类别”,而不是“参数类型”。 “s”和“S”在参数类别表中被视为“一般”而不是“字符”。这就是您可以使用点精度的原因。

关于java - 使用 SimpleFormatter 限制字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com