我需要导入一个文件并将其转换为字符串:
示例输入文件是:
#doc source topic proportion ...
0 src/main/resources/alpha1234 128 0.0651366607249073 26 0.05985658726301475 105 0.047919029870909846 173 0.04677118781397669
Run Code Online (Sandbox Code Playgroud)
我只需要文件第二行的一部分字符串。那是来自第二行的第三个字。
预期输出字符串
128 0.0651366607249073 26 0.05985658726301475 105 0.047919029870909846 173 0.04677118781397669
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试过:
val inFile = Source.fromResource("FileName").getLines.mkString(" ").drop(1)
val out = new BufferedWriter(new FileWriter("src/main/resources/newResult.txt"))
out.write(inFile)
out.close()
Run Code Online (Sandbox Code Playgroud)
但是,它不会删除第一行,而只会删除第一个字母。
问题是你mkString先打电话,然后drop. 函数mkString转换Iterator[String]为String并在您调用drop它时适用于chars。让我们颠倒顺序:
val lines = Source
.fromResource("FileName")
.getLines
.toList // we convert Iterator to List to allow pattern matching
.drop(1) match { // we drop 1st line and then match the rest
// we match 1st line, split it by space, drop 2 first words and then assemble everything back together
case x :: xs => x.split(" ").drop(2).mkString(" ") :: xs
}
val inFile = lines.mkString(" ")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
596 次 |
| 最近记录: |