更新时间:2024-10-18 GMT+08:00
读取HDFS指定文件内容
功能简介
获取HDFS上某个指定文件的内容。过程为:
- 使用FileSystem实例的open方法获取读取文件的输入流。
- 使用该输入流读取HDFS的指定文件的内容。
在完成后,需关闭所申请资源。
代码样例
如下是读文件的代码片段,详细代码请参考com.huawei.bigdata.hdfs.examples中的HdfsExample类。
/**
* 读文件
*
* @throws java.io.IOException
*/
private void read() throws IOException {
String strPath = DEST_PATH + File.separator + FILE_NAME;
Path path = new Path(strPath);
FSDataInputStream in = null;
BufferedReader reader = null;
StringBuffer strBuffer = new StringBuffer();
try {
in = fSystem.open(path);
reader = new BufferedReader(new InputStreamReader(in));
String sTempOneLine;
// write file
while ((sTempOneLine = reader.readLine()) != null) {
strBuffer.append(sTempOneLine);
}
LOG.info("result is : " + strBuffer.toString());
LOG.info("success to read.");
} finally {
// make sure the streams are closed finally.
IOUtils.closeStream(reader);
IOUtils.closeStream(in);
}
}
父主题: 开发HDFS应用