Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 将print()输出重定向到字符串而不是stdout_Kotlin_Inputstream_Stdout - Fatal编程技术网

Kotlin 将print()输出重定向到字符串而不是stdout

Kotlin 将print()输出重定向到字符串而不是stdout,kotlin,inputstream,stdout,Kotlin,Inputstream,Stdout,我试图将对象的print()函数的stdout重定向到字符串变量中 为此,我使用以下Java导入(在Kotlin中): 以及以下功能: fun index(): String { val df_out = DataFrame.fromJson("https://jsonplaceholder.typicode.com/posts") val pipeOut = PipedOutputStream() val pipeIn = PipedInput

我试图将对象的print()函数的stdout重定向到字符串变量中

为此,我使用以下Java导入(在Kotlin中):

以及以下功能:

fun index(): String {

        val df_out = DataFrame.fromJson("https://jsonplaceholder.typicode.com/posts")
        val pipeOut = PipedOutputStream()
        val pipeIn = PipedInputStream(pipeOut)
        System.setOut(PrintStream(pipeOut));
        df_out.print(maxRows = 10)
        val dfAsStr = pipeIn.bufferedReader().use { it.readText() }
        return dfAsStr
    }
其思想是将
print()
方法的输出捕获到
PipedInputStream
中,以便能够将其作为(处理过的)字符串返回


此函数代码不终止

你可以试试这个。如果我没弄错你的问题

fun index(): String {
    val df_out = DataFrame.fromJson("https://jsonplaceholder.typicode.com/posts")
    val outStream = ByteArrayOutputStream().apply { System.setOut(PrintStream(df_out)) }
    df_out.print(maxRows = 10)
    return outStream.toString()
}
fun index(): String {
    val df_out = DataFrame.fromJson("https://jsonplaceholder.typicode.com/posts")
    val outStream = ByteArrayOutputStream().apply { System.setOut(PrintStream(df_out)) }
    df_out.print(maxRows = 10)
    return outStream.toString()
}