【问题标题】:Read the data from HDFS using Scala使用 Scala 从 HDFS 读取数据
【发布时间】:2017-05-26 01:40:56
【问题描述】:

我是 Scala 新手。如何使用 Scala(不使用 Spark)从 HDFS 读取文件? 当我用谷歌搜索时,我只发现了 HDFS 的写入选项。

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.PrintWriter;

/**
* @author ${user.name}
*/
object App {

//def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)

def main(args : Array[String]) {
println( "Trying to write to HDFS..." )
val conf = new Configuration()
//conf.set("fs.defaultFS", "hdfs://quickstart.cloudera:8020")
conf.set("fs.defaultFS", "hdfs://192.168.30.147:8020")
val fs= FileSystem.get(conf)
val output = fs.create(new Path("/tmp/mySample.txt"))
val writer = new PrintWriter(output)
try {
    writer.write("this is a test") 
    writer.write("\n")
}
finally {
    writer.close()
    println("Closed!")
}
println("Done!")
}

}

请帮助我。如何使用 scala 从 HDFS 读取文件或加载文件。

【问题讨论】:

标签: scala hdfs


【解决方案1】:

其中一种方式(有点功能风格)可能是这样的:

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import java.net.URI
import scala.collection.immutable.Stream

val hdfs = FileSystem.get(new URI("hdfs://yourUrl:port/"), new Configuration()) 
val path = new Path("/path/to/file/")
val stream = hdfs.open(path)
def readLines = Stream.cons(stream.readLine, Stream.continually( stream.readLine))

//This example checks line for null and prints every existing line consequentally
readLines.takeWhile(_ != null).foreach(line => println(line))

如果您有兴趣,您还可以查看this articleherehere,这些问题看起来与您的问题相关,并且包含工作(但更类似于Java)的代码示例。

【讨论】:

  • 什么是URI?如何导入?
  • 我通过将 URI 导入为 import java.net.URI 并将其设置为 hdfs:/// 来实现此功能,因为我的 Scala 服务与 HDFS 名称服务器主机在同一节点中运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
相关资源
最近更新 更多