在 Scala 中,如何读取文件HDFS并将内容分配给变量。我知道如何读取文件并且可以打印它。但是如果我尝试将内容分配给一个字符串,它将输出为 Unit()。下面是我试过的代码。
val dfs = org.apache.hadoop.fs.FileSystem.get(config);
val snapshot_file = "/path/to/file/test.txt"
val stream = dfs.open(new Path(snapshot_file))
def readLines = Stream.cons(stream.readLine, Stream.continually( stream.readLine))
readLines.takeWhile(_ != null).foreach(line => println(line))
Run Code Online (Sandbox Code Playgroud)
上面的代码正确打印输出。但是如果我尝试将输出分配给一个字符串,我会得到正确的输出。
val snapshot_id = readLines.takeWhile(_ != null).foreach(line => println(line))
snapshot_id: Unit = ()
Run Code Online (Sandbox Code Playgroud)
将内容分配给变量的正确方法是什么?
您需要使用mkString. 由于println返回Unit()它获取存储在您的变量,如果你叫println你流
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://namenode:port/"), new org.apache.hadoop.conf.Configuration())
val path = new org.apache.hadoop.fs.Path("/user/cloudera/file.txt")
val stream = hdfs.open(path)
def readLines = scala.io.Source.fromInputStream(stream)
val snapshot_id : String = readLines.takeWhile(_ != null).mkString("\n")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4398 次 |
| 最近记录: |