1.Copy a file from the local file system to HDFS

The srcFile variable needs to contain the full name (path + file name) of the file in the local file system.

The dstFile variable needs to contain the desired full name of the file in the Hadoop file system.

 Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path srcPath = new Path(srcFile);
Path dstPath = new Path(dstFile);
hdfs.copyFromLocalFile(srcPath, dstPath);

2.Create HDFS file

The fileName variable contains the file name and path in the Hadoop file system.

The content of the file is the buff variable which is an array of bytes.

 //byte[] buff - The content of the file
//创建了一个HDFS文件,并且把buff数组的内容写到了HDFS文件中。
Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
FSDataOutputStream outputStream = hdfs.create(path);
outputStream.write(buff, 0, buff.length);

3.Rename HDFS file

In order to rename a file in Hadoop file system, we need the full name (path + name) of

the file we want to rename. The rename method returns true if the file was renamed, otherwise false.

   Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path fromPath = new Path(fromFileName);
Path toPath = new Path(toFileName);
boolean isRenamed = hdfs.rename(fromPath, toPath);

4.Delete HDFS file

In order to delete a file in Hadoop file system, we need the full name (path + name)

of the file we want to delete. The delete method returns true if the file was deleted, otherwise false.

   Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
boolean isDeleted = hdfs.delete(path, false); //Recursive delete:估计true是递归删除该目录下面的文件。
Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
boolean isDeleted = hdfs.delete(path, true);

5.Get HDFS file last modification time

In order to get the last modification time of a file in Hadoop file system,

we need the full name (path + name) of the file.

   Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
FileStatus fileStatus = hdfs.getFileStatus(path);
long modificationTime = fileStatus.getModificationTime

6.Check if a file exists in HDFS

In order to check the existance of a file in Hadoop file system,

we need the full name (path + name) of the file we want to check.

The exists methods returns true if the file exists, otherwise false.

 Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
boolean isExists = hdfs.exists(path);

7.Get the locations of a file in the HDFS cluster

A file can exist on more than one node in the Hadoop file system cluster for two reasons:

Based on the HDFS cluster configuration, Hadoop saves parts of files on different nodes in the cluster.

Based on the HDFS cluster configuration, Hadoop saves more than one copy of each file on different nodes for redundancy (The default is three).

 Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
Path path = new Path(fileName);
FileStatus fileStatus = hdfs.getFileStatus(path);
BlockLocation[] blkLocations = hdfs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
int blkCount = blkLocations.length;
for (int i = 0; i < blkCount; i++) {
String[] hosts = blkLocations[i].getHosts();
// Do something with the block hosts
}

8. Get a list of all the nodes host names in the HDFS cluster

his method casts the FileSystem Object to a DistributedFileSystem Object.

This method will work only when Hadoop is configured as a cluster.

Running Hadoop on the local machine only, in a non cluster configuration will  cause this method to throw an Exception.

   Configuration config = new Configuration();
FileSystem fs = FileSystem.get(config);
DistributedFileSystem hdfs = (DistributedFileSystem) fs;
DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();
String[] names = new String[dataNodeStats.length];
for (int i = 0; i < dataNodeStats.length; i++) {
names[i] = dataNodeStats[i].getHostName();
}

遇到的问题及解决:

1.文件append的问题

hadoop的版本1.0.4以后,API中已经有了追加写入的功能,但不建议在生产环境中使用,原因如下:Does HDFS allow appends to files? This is currently set to false because there are bugs in the "append code" and is not supported in any prodction cluster.
如果要测试的话,需要把dfs.support.appen的参数设置为true,不然客户端写入的时候会报错:

Exception in thread "main" org.apache.hadoop.ipc.RemoteException: java.io.IOException: Append to hdfs not supported. Please refer to dfs.support.append configuration parameter.

解决:修改namenode节点上的hdfs-site.xml。

  <property>
<name>dfs.support.append</name>
<value>true</value>
</property>

2.在Hadoop-1.0.4和Hadoop-2.2的使用append时,需求:追加写入文件,如果文件不存在,需求先创建。

异常:

Exception in thread "main" org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException: failed to create file /huangq/dailyRolling/mommy-dailyRolling for DFSClient_-1456545217 on client 10.1.85.243 because current leaseholder is trying to recreate file.
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.recoverLeaseInternal(FSNamesystem.java:1374)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.startFileInternal(FSNamesystem.java:1246)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.appendFile(FSNamesystem.java:1426)
at org.apache.hadoop.hdfs.server.namenode.NameNode.append(NameNode.java:643)
at sun.reflect.GeneratedMethodAccessor25.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)

代码版本1:(出现上述报错的代码)

 FileSystem fs = FileSystem.get(conf);
Path dstPath = new Path(dst);
if (!fs.exists(dstPath)) {
fs.create(dstPath);
}
FSDataOutputStream fsout = fs.append(dstPath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fsout));

异常的原因:FSDataOutputStream create(Path f) 产生了一个输出流,创建完后需要关闭。

解决:创建完文件之后,关闭流FSDataOutputStream。

FileSystem fs = FileSystem.get(conf);
Path dstPath = new Path(dst);
if (!fs.exists(dstPath)) {
fs.create(dstPath).close();
}
FSDataOutputStream fsout = fs.append(dstPath);

Hadoop HDFS文件常用操作及注意事项(更新)的更多相关文章

  1. Hadoop HDFS文件常用操作及注意事项

    Hadoop HDFS文件常用操作及注意事项 1.Copy a file from the local file system to HDFS The srcFile variable needs t ...

  2. [b0002] Hadoop HDFS cmd常用命令练手

    目的: 学会HDFS CLI 常用操作 环境: Hadoop 2.6.4 伪分布式版 环境搭建参考本博客前篇文章: 伪分布式 hadoop 2.6.4 帮助: hadoop@ssmaster:~$ h ...

  3. python 异常处理、文件常用操作

    异常处理 http://www.jb51.net/article/95033.htm 文件常用操作 http://www.jb51.net/article/92946.htm

  4. go语言之进阶篇文件常用操作接口介绍和使用

    一.文件常用操作接口介绍 1.创建文件 法1: 推荐用法 func Create(name string) (file *File, err Error) 根据提供的文件名创建新的文件,返回一个文件对 ...

  5. Python基础灬文件常用操作

    文件常用操作 文件内建函数和方法 open() :打开文件 read():输入 readline():输入一行 seek():文件内移动 write():输出 close():关闭文件 写文件writ ...

  6. hdfs 文件系统命令操作

    hdfs 文件系统命令操作 [1]hdfs dfs -ls [目录]. 显示所有文件 hdfs dfs -ls -h /user/20170214.txt 显示文件时,文件大小以人易读的形式显示 [2 ...

  7. Hadoop HDFS文件操作

    1.创建目录 import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.ha ...

  8. HDFS文件读写操作(基础基础超基础)

    环境 OS: Ubuntu 16.04 64-Bit JDK: 1.7.0_80 64-Bit Hadoop: 2.6.5 原理 <权威指南>有两张图,下次po上来好好聊一下 实测 读操作 ...

  9. Spark环境搭建(二)-----------HDFS shell 常用操作

    配置好HDFS,也学习了点HDFS的简单操作,跟Linux命令相似 1)  配置Hadoop的环境变量,类似Java的配置 在 ~/.bash_profile 中加入 export HADOOP_HO ...

随机推荐

  1. c# HttpWebRequest与HttpWebResponse(转)

    如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧.本文章会对Http请求时的Get和Post方式进行详细的说明,在请求时的参数怎么发送,怎么带Cookie,怎么设置证 ...

  2. 腾讯WEB前端开发三轮面试经历及面试题

    [一面]~=110分钟  2013/04/24 11:20  星期三 进门静坐30分钟做题. 填空题+大题+问答题 >>填空题何时接触电脑 何时接触前端运算符 字符串处理        延 ...

  3. UML中的六种关系的比较与学习

    通过不断的学习并绘制UML图,整个画图的过程中深刻体会到其核心部分还是理解事物之间的关系,总结六大关系来深入学习,主要关系有六种:继承.实现.依赖.关联.聚合.组合. 区别于联系:         1 ...

  4. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):1 概述

    本文档尝试用Video Toolbox进行H.265(HEVC)硬件编码,视频源为iPhone后置摄像头.去年做完硬解H.264,没做编码,技能上感觉有些缺失.正好刚才发现CMFormatDescri ...

  5. 面试问到的Spring

    一.介绍Spring 1.主要使用了基本的javabean代替的Ejb  Ejb:服务端的组件模型,设计目标应用部署分布在应用程序,把已经做好的编好的程序,打包放在服务 端执行,凭借java跨平台的优 ...

  6. Android Studio:Gradle常用命令

    Android Studio中自带Terminal,可以直接使用gradle命令,不必另开命令窗口,相当方便,下面总结一下常用的命令: 1.查看Gradle版本号      ./gradlew -v  ...

  7. BAT CMD 批处理文件脚本 -1

    http://www.cnblogs.com/linglizeng/archive/2010/01/29/Bat-CMD-ChineseVerion.html 1.               综述 ...

  8. angular入门系列教程4

    主题: 本篇主要目的就是继续完善home页下的index子页面的内容,处理一个列表,进行增删改查过滤等操作. 效果图: 细节: 主要的更改有两个,一个是修改模板index.html,还有就是增加控制器 ...

  9. 编写一个递归函数,输出vector对象的内容

    // test14.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> #include< ...

  10. 【BZOJ】【2594】【WC2006】水管局长数据加强版

    LCT 动态维护MST嘛……但是有删边= =好像没法搞的样子 离线记录所有修改&询问,倒序处理,就可以变删边为加边了- 论如何用LCT维护最小生成树:先搞出一棵最小生成树,然后每次加边(u,v ...