Kotlin String最大长度?(Kotlin文件中的String过长,无法编译)

问题描述 投票:2回答:1

根据 本回答 Java最多可以容纳2^31-1个字符。我试图做基准测试和东西,所以我试着创建大量的字符串,并将其写入这样的文件。

import java.io.*

fun main() {
    val out = File("ouput.txt").apply { createNewFile() }.printWriter()
    sequence {
        var x = 0
        while (true) {
            yield("${++x} ${++x} ${++x} ${++x} ${++x}")
        }
    }.take(5000).forEach { out.println(it) }
    out.close()
}

然后... output.txt 文件的内容是这样的。

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
// ... 5000 lines

然后我把文件中的所有内容复制到一个字符串中,以便对一些函数进行基准测试,所以这就是它的样子。

import kotlin.system.*

fun main() {
    val inputs = """
        1 2 3 4 5
        6 7 8 9 10
        11 12 13 14 15
        16 17 18 19 20
        21 22 23 24 25
        // ... 5000 lines
        24986 24987 24988 24989 24990
        24991 24992 24993 24994 24995
        24996 24997 24998 24999 25000

    """.trimIndent()
    measureNanoTime {
        inputs.reader().forEachLine { line ->
            val (a, b, c, d, e) = line.split(" ").map(String::toInt)
        }
    }.div(5000).let(::println)
}

这个文件字符串的总字符数是138894个

字符串最多可以容纳2147483647个。

但Kotlin代码无法编译(最后一个文件) 它抛出了编译错误。

e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: wrong bytecode generated
// more lines
The root cause java.lang.IllegalArgumentException was thrown at: org.jetbrains.org.objectweb.asm.ByteVector.putUTF8(ByteVector.java:246)
    at org.jetbrains.kotlin.codegen.TransformationMethodVisitor.visitEnd(TransformationMethodVisitor.kt:92)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.endVisit(FunctionCodegen.java:971)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: UTF8 string too large

这里是异常日志和stacktrace: https:/gist.github.comAnimeshz1a18a7e99b0c0b913027b7fb36940c07。

java string kotlin string-length
1个回答
2
投票

java类文件有限制,字符串常量的长度必须适合16位,即65535字节(不是字符)是源代码中字符串的最大长度。

类文件格式

© www.soinside.com 2019 - 2024. All rights reserved.