String.format / Formatter 中的错误?

发布于 2024-10-18 04:06:15 字数 841 浏览 7 评论 0原文

出于好奇,我尝试创建一个非常大的字符串。事实证明 Formatter 类因宽度规格超过 Integer.MAX_VALUE 而阻塞:

// Produces an empty string. (2147483648 = Integer.MAX_VALUE + 1)
String.format("%2147483648s", "");

因此我去验证它是否确实符合规格。但它所说的只是

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

因此,在我看来,正确的行为是抛出 IllegalFormatWidthException

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


另外,应该注意的是,如果在宽度前面放置一个 - (以使输出左对齐):

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

它确实会抛出一个 < code>MissingFormatWidthException (据我所知,这似乎是正确的行为)。

(我使用的是 OpenJDK 版本 1.6.0_20。)

Out of curiosity I tried to create a really large string. It turned out that the Formatter class chokes on width specifications exceeding Integer.MAX_VALUE:

// Produces an empty string. (2147483648 = Integer.MAX_VALUE + 1)
String.format("%2147483648s", "");

So I went off to verify that it was indeed according to spec. But all it says is

If the format specifier contains a width or precision with an invalid value or which is otherwise unsupported, then a IllegalFormatWidthException or IllegalFormatPrecisionException respectively will be thrown.

So in my opinion the correct behavior would be to throw an IllegalFormatWidthException.

Is this bug (?) documented somewhere? (If not, I'll go report it.)


Also, it should be noted that if one puts a - in front of the width (to left-justify the output):

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

it indeed throws a MissingFormatWidthException (which, as I see it, seems to be correct behavior).

(I'm using OpenJDK version 1.6.0_20.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街道布景 2024-10-25 04:06:15

我认为你是对的,这是一个错误:如果存在任何异常,它应该抛出 IllegalFormatWidthException。

该异常的 javadoc 说“当格式宽度为 -1 以外的负值或不受支持时抛出未经检查的异常”,奇怪的是,它没有具体提及太大的值。我认为“否则不受支持”条款使得这是一个合理的例外。

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.

哎呦我呸! 2024-10-25 04:06:15

格式/格式化程序文档应该解决这种情况,这是由于尝试将超过字符串最大长度的字符串写入格式的附加程序而引起的。如果您确实需要这样做,则必须使用流。

请参阅Java 中字符串的最大长度 - 调用 length() 方法

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文