简体   繁体   English

使用指向HDFS的URI创建文件实例

[英]Create File instance with URI pointing to HDFS

Is it possible to create a file instance by putting the uri of my HDFS as File class's constructor? 是否可以通过将HDFS的uri用作File类的构造函数来创建文件实例? For example: 例如:

val conf = new Configuration()
conf.addResource(hdfsCoreSitePath)
conf.addResource(hdfsHDFSSitePath)

val uri = conf.get("fs.default.name")
val file = new File(uri + pathtothefile)

Then, with the file instance, I wish to access the file list with the functions provided by File class such as file.list() to returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. 然后,对于文件实例,我希望使用File类提供的功能file.list()例如file.list()访问文件列表,以返回一个字符串数组,命名该抽象路径名表示的目录中的文件和目录。 I tried the code but it return null on the file.list() . 我尝试了代码,但在file.list()上返回null

The method below is not recommended as I am trying to writing the same codebase for normal file system and hdfs to achieve code reusable. 不建议使用以下方法,因为我正在尝试为普通文件系统和hdfs编写相同的代码库,以实现可重用的代码。

val fileSystem = FileSystem.get(conf)
val status = fileSystem.listStatus(new Path(filepath))
status.map(x => ...

fs.default.name is deprecated. fs.default.name已弃用。 Try to use fs.defaultFS and make sure this property is available in the core-site.xml file you are referring using the below command 尝试使用fs.defaultFS并确保使用以下命令在您引用的core-site.xml文件中可用此属性

conf.addResource(hdfsCoreSitePath)

https://hadoop.apache.org/docs/r2.7.1/hadoop-project-dist/hadoop-common/core-default.xml https://hadoop.apache.org/docs/r2.7.1/hadoop-project-dist/hadoop-common/core-default.xml

The regular built-in Java/Scala File APIs will not work for HDFS files. 常规的内置Java / Scala File API不适用于HDFS文件。 The protocol and implementation are too different. 协议和实现太不同了。 You have to use the Hadoop API to access HDFS files as in your second example. 与第二个示例一样,您必须使用Hadoop API来访问HDFS文件。

The good news, though, is that the Hadoop API will work for non-HDFS files (regular files). 不过,好消息是Hadoop API 将可用于非HDFS文件(常规文件)。 So that code is reusable. 这样该代码是可重用的。 Just use a URI like: file:///foo/bar for a local file. 只需使用URI: file:///foo/bar作为本地文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM