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

基于eclipse的hadoop开发-----HDFS API学习

2012-04-19 16:21 621 查看
环境:ubuntu8.04.4 hadoop1.0.2 eclipse3.7.2

概要:本文主要是记录HDFS中常用API的使用,如文件上传、创建文件、重命名、删除、读取文件内容等。

一、实验步骤

1、启动Hadoop,切换到超级用户
gqy@localhost:/usr/local/hadoop-1.0.2$ su
root@localhost:/usr/local/hadoop-1.0.2# bin/hadoop namenode -format
root@localhost:/usr/local/hadoop-1.0.2# bin/start-all.sh

2、打开Eclipse,新建一个工程。
File-->New-->Other-->Map/Reduce Project

3、新建类,输入代码。运行时点 Run On Hadoop,观察控制台的输出信息,同时可以在终端用命令查看hdfs的内容 或者 在eclipse中右键DFS 选择disconnect,即可实现刷新文件系统显示

主方法

/*
*main
* */
public static void main(String[] args) throws IOException
{
//-------------test uploadLocalfile-----------
String src ="/home/gqy/testFileOperate.txt";
String dst = "/";

HadoopFileOperate testFileOperate = new HadoopFileOperate();
testFileOperate.uploadLocalfileToHdfs(src, dst);

//-----------test create HDFS file------------
FileInputStream file = new FileInputStream(src);
byte[] content = new byte[file.available()];
file.read(content);  //file the content arrays

String newFileName = "/tmp/testFileOperate/newFile.txt";
testFileOperate.createNewHdfsFile(newFileName, content);

//-----------test rename HDFS file--------------
String rename = "/new2.cpp";
testFileOperate.renameHdfsFile(newFileName, rename);

//----------test make a new dir in Hdfs-------
String dir = "/tmp/testFileOperate/test";
testFileOperate.mkdir(dir);

//-----------test delete Hdfs file------------
testFileOperate.deleteHdfsFile("/tmp/testFileOperate/newFile.txt");

//-----------test read Hdfs file
byte[] readContent = testFileOperate.readHdfsFile(rename);
if (readContent != null)
{
String contentString = new String(readContent);
System.out.println("OK,read content: \n"+contentString);
}

}


二、部分错误的分析

1、Hdfs中重命名文件失败的原因:

(1)指定的src文件,不是hdfs文件

(2)在hdfs中已存在该名字的文件

我感觉重命名就是把原来的文件删除,在新建一个文件

2、删除文件失败(delete):

当hdfs.delete(src,flag)中,src是一个目录时,flag必须为true,实现全部删除。若flag为false,则会抛出异常

3、上传文件失败:

目标路径必须是在命令中能显示的:

hadoop fs -ls /

若此时只显示 /home/gqy/hadoop

那么,目标路径取 /home/gqy/tmp 就会上传失败,可以取/home/gqy/hadoop/test
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: