您的位置:首页 > 大数据 > Hadoop

远程HDFS文件的操作

2016-09-12 23:19 746 查看
  因为手头项目涉及到远程HDFS文件的操作,所以打算学习一下相关操作。目前,网络上有很多操作HDFS文件的代码,但是它们基本上都没有描述清楚Configuration相关问题。经过摸索,终于实现远程HDFS文件读写的完整流程,在此希望各位看官交流学习。

  HDFS文件操作依赖的jar包是通过maven下载的,其相关依赖如下:

<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${cdh.hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${cdh.hadoop.version}</version>
</dependency>
</dependencies>


以上依赖中version处根据实际情况填写。

HDFS文件的操作用到类有以下3个:

org.apache.hadoop.conf.Configuration;

org.apache.hadoop.fs.FileSystem;

org.apache.hadoop.fs.Path;

Configuration

  hadoop既没有使用java.util.Properties管理配置文件,也没有使用Apache Jakarta Commons Configuration管理配置文件,而是使用其独有的配置文件管理系统org.apache.hadoop.conf.Configuration,该配置管理系统提供自已的API。博文http://blog.csdn.net/hadoop_/article/details/9365075对Configuration描述较为清晰,此处不再描述。另外,操作HDFS文件需要用到hadoop目录中的core-site.xml和hdfs-site.xml文件。

 

代码片段

配置:

Configuration conf = new Configuration();

FileSystem hdfs = FileSystem.get(URI.create(“hdfs://nameservice/path”), conf, “username”);

HDFS文件读写操作:

public void writerContentToHdfs(String hdfsFile, String content) {
OutputStream os = null;
OutputStreamWriter osw = null;
try {
Path file = new Path(hdfsFile);
if (!this.hdfs.exists(file)) { os = this.hdfs.create(file); }
else { os = this.hdfs.append(file); }
osw = new OutputStreamWriter(os);
osw.write(content);
osw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) { os.close(); }
if (osw != null) { osw.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
}

public String readContentFromHdfs(String hdfsFile) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
Path file = new Path(hdfsFile);
if (!this.hdfs.exists(file)) { return null; }

is = this.hdfs.open(file);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (is != null) { is.close(); }
if (isr != null) { isr.close(); }
if (br != null) { br.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}

return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: