您的位置:首页 > 编程语言 > Java开发

java操作hdfs实例

2016-03-15 17:24 549 查看
环境:window7+eclipse+vmware虚拟机+搭建好的hadoop环境(master、slave01、slave02)

内容:主要是在windows环境下,利用eclipse如何来操作hdfs,如上传文件、删除文件、创建文件夹、查看节点信息等。

eclipse开发环境的搭建,请参考:http://www.cnblogs.com/bookwed/p/4816521.html

1、新建maven项目,(主要是因为要引入一些jar包,除非是特别清楚要引入哪些jar包可以不用建maven项目)

  创建web项目的细节不作说明了,下面把关键的pom依赖信息贴出来,这里主要是hadoop的基础包和hdfs包  

<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>


2、创建普通java类,编写代码,贴出部分代码,如下:

public class OperaHDFS {
public static void main(String args[]) throws IOException {
//测试 创建新文件
//byte[] contents = "hello world 世界你好\n--created by eclipse\n".getBytes();
//createFile("/eclipse/first.txt", contents);    //或 createFile("hdfs://192.168.137.56:9000/eclipse/first.txt", contents);

//测试 上传本地文件
//uploadFile("D:\\c.txt", "/eclipse/");

//测试重命名
//rename("/eclipse/c.txt", "/eclipse/cc.txt");

//测试删除文件
//delete("/eclipse/cc.txt"); //使用相对路径
//delete("/eclipse2");    //删除目录

//测试新建目录
//mkdir("/eclipse2/");

//测试读取文件
//readFile("/eclipse/first.txt");

//测试文件是否存在
//fileIsExists("/eclipse/first.txt");

getNodeMsgHdfs();

}

//1、创建新文件(直接生成指定路径下的first.txt,即:/eclipse/first.txt)
public static void createFile(String dst, byte[] contents) throws IOException {
Configuration conf = new Configuration();
System.out.println("-----------:"+conf);
conf.set("fs.defaultFS", "hdfs://192.168.137.56:9000");    //master
FileSystem fs = FileSystem.get(conf);
Path dstPath = new Path(dst); // 目标路径
// 打开一个输出流
FSDataOutputStream outputStream = fs.create(dstPath);
outputStream.write(contents);
outputStream.close();
fs.close();
System.out.println("文件创建成功!");
}

//2、上传本地文件
public static void uploadFile(String src, String dst) throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.137.56:9000");    //master
FileSystem fs = FileSystem.get(conf);
Path srcPath = new Path(src); // 源路径
Path dstPath = new Path(dst); // 目标路径
// 调用文件系统的文件复制函数,前面参数是指是否删除原文件,true为删除,默认为false
fs.copyFromLocalFile(false, srcPath, dstPath);

// 打印文件路径
System.out.println("Upload to " + conf.get("fs.default.name"));
//列出指定路径下的所有文件
System.out.println("------------list files------------" + "\n");
FileStatus[] fileStatus = fs.listStatus(dstPath);
for (FileStatus file : fileStatus) {
System.out.println(file.getPath()+"--"+file.getGroup()+"--"+file.getBlockSize()+"--"+file.getLen()+"--");
}
fs.close();
}
  }


3、完整代码,请参考: http://pan.baidu.com/s/1eRsXp6M 密码: 9tg9,里面还有一些关于压缩文件的例子。

  

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