我试图创建一个非常大的字符串。事实证明, Formatter 类窒息宽度规格超过Integer.MAX_VALUE

// Produces an empty string. (2147483648 = Integer.MAX_VALUE + 1)
String.format("%2147483648s", "");
. 所以我走了去验证它确实根据规格。但它所说的只是

如果格式说明符包含具有无效值的宽度或精度,或者不支持,则分别抛出IllegalFormatWidthException或IllegalFormatPrecisionException。

所以在我看来,正确的行为是抛出一个生成的。

是这个错误(?)记录在某个地方? (如果没有,我会报告它。)


也,应该注意的是,如果一个人在宽度前面放置一个IllegalFormatWidthException(以左对齐输出):

String.format("%-2147483648s", "");
.

确实抛出了一个生成的(当我看到它时,似乎是正确的行为)。

(我正在使用OpenJDK 1.6.0_20。)

有帮助吗?

解决方案

I think you're right and that it's a bug: it should throw IllegalFormatWidthException, if any existing exception.

The javadoc for that exception says "Unchecked exception thrown when the format width is a negative value other than -1 or is otherwise unsupported", which oddly doesn't specifically mention values that are too large. I think the "otherwise unsupported" clause makes this a reasonable exception to throw.

其他提示

The format/formatter documentation should address this case, which is caused by trying to write a string to the format's appender that exceeds the maximum length of a string. If you actually needed to do this, you would have to use a stream.

See String's Maximum length in Java - calling length() method

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top