hdfs文件操作基本方法(1)
2011-05-05 14:26
323 查看
DFSOperater.java
import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.*; import org.apache.hadoop.hdfs.protocol.*; import java.util.Date; public class DFSOperater { /** * @param args */ public static void main(String[] args) { Configuration conf = new Configuration(); try { // Get a list of all the nodes host names in the HDFS cluster FileSystem fs = FileSystem.get(conf); DistributedFileSystem hdfs = (DistributedFileSystem) fs; DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats(); String[] names = new String[dataNodeStats.length]; System.out.println("list of all the nodes in HDFS cluster:"); // print // info for (int i = 0; i < dataNodeStats.length; i++) { names[i] = dataNodeStats[i].getHostName(); System.out.println(names[i]); // print info } Path f = new Path("/user/cluster/dfs.txt"); // check if a file exists in HDFS boolean isExists = fs.exists(f); System.out.println("The file exists? [" + isExists + "]"); // if the file exist, delete it if (isExists) { boolean isDeleted = hdfs.delete(f, false);// fase : not // recursive if (isDeleted) System.out.println("now delete " + f.getName()); } // create and write System.out.println("create and write [" + f.getName() + "] to hdfs:"); FSDataOutputStream os = fs.create(f, true, 0); for (int i = 0; i < 10; i++) { os.writeChars("test hdfs "); } os.writeChars("/n"); os.close(); // get the locations of a file in HDFS System.out.println("locations of file in HDFS:"); FileStatus filestatus = fs.getFileStatus(f); BlockLocation[] blkLocations = fs.getFileBlockLocations(filestatus, 0, filestatus.getLen()); int blkCount = blkLocations.length; for (int i = 0; i < blkCount; i++) { String[] hosts = blkLocations[i].getHosts(); // Do sth with the block hosts System.out.println(hosts); } // get HDFS file last modification time long modificationTime = filestatus.getModificationTime(); // measured // in // milliseconds // since // the // epoch Date d = new Date(modificationTime); System.out.println(d); // reading from HDFS System.out.println("read [" + f.getName() + "] from hdfs:"); FSDataInputStream dis = fs.open(f); System.out.println(dis.readUTF()); dis.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
相关文章推荐
- 利用 Hadoop FileSystem moveToLocalFile 方法下载文件 实现HDFS操作
- HDFS下的基本文件操作
- hadoop-3.0.0-beta1运维手册(008):hdfs3.0.0基本操作-查看HDFS文件系统、查看文本文件、使用帮助
- 练习20:函数和文件操作的基本方法
- 文件的基本操作(自用)打表的找规律的便利方法
- C#操作本地文件及保存文件到数据库的基本方法总结
- .net操作文件的基本方法总结
- HDFS 基本文件操作API
- CompressUtils相关代码,java中文件压缩或解压已经文件的基本操作等方法
- File文件的一些基本方法和操作
- Java常用的一些多媒体文件基本操作方法简介
- Linux下vim基本操作和清空文件内容的常用方法
- C#操作word的一些基本方法(word打印,插入文件,插入图片,定位页眉页脚,去掉横线)
- C#操作word的一些基本方法(word打印,插入文件,插入图片,定位页眉页脚,去掉横线)
- Hadoop (HDFS)分布式文件系统基本操作
- Python操作文件的基本方法
- CompressUtils相关代码,java中文件压缩或解压已经文件的基本操作等方法
- HDFS文件系统的基本操作 Hadoop权威指南
- Hadoop (HDFS)分布式文件系统基本操作 推荐
- C#操作word的一些基本方法(word打印,插入文件,插入图片,定位页眉页脚,去掉横线)