HDFS的JAVA接口API操作实例
时间:2010-06-02 来源:qkshan
主要参考这篇文章 http://myjavanotebook.blogspot.com/2008/05/hadoop-file-system-tutorial.html
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(); |
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 |
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(); |
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(); |
Configuration config = new Configuration(); |
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(); |
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();
BlockLocation[] blkLocations = hdfs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()); |
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(); |
/* |
编译后拷贝到node1上面运行,杯具,不会用Eclipse插件
[cluster /opt/hadoop/source]$cp /opt/winxp/hadoop/dfs_operator.jar . |
运行成功!查看输出文件
[cluster /opt/hadoop/source]$hadoop fs -cat dfs.txt |