Hadoop——Eclipse插件操作HDFS

本节目标:

1、掌握应用hadoop-eclipse-plugin对HDFS的管理操作

2、掌握应用eclipse编码方式简单操作HDFS

一、插件管理

1、修改C:\Windows\System32\drivers\etc下的hosts文件

 

2、为了解决用户权限无法写入的问题

(1)在系统的环境变量中添加HADOOP_USER_NAME。


(2)更改系统的用户名,与有hadoop用户名保持一致。


采用以上一种方法即可。

3、将hadoop-eclipse-plugin插件添加到plugins目录下


4、启动eclipse

5、按以下步骤操作HDFS





二、编码操作HDFS

public class HDFSDemo {
Configuration conf;//声明配置信息
FileSystem fs ;//定义文件系统抽象类
private FSDataOutputStream outputStream;//定义HDFS文件输出流
private Writer writer;
@Before
public void begin() throws IOException{
conf = new Configuration();//加载src下的配置文件
fs = FileSystem.get(conf);//实例化HDFS对象
}
@After
public void end(){
try {
fs.close();//关闭与文件系统的连接
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建文件夹
* @throws IOException
*/
@Test
public void mkdir() throws IOException{
Path path = new Path("/tmp");
fs.mkdirs(path);
}
/**
* 上传文件到HDFS
* @throws IOException
*/
@Test
public void upload() throws IOException{
Path path = new Path("/tmp/test");
outputStream = fs.create(path);//实例化输出流对象
FileUtils.copyFile(new File("f:" + File.separator + "test.txt"), outputStream);
}
/**
* 查看HDFS文件列表
* @throws IOException 
* @throws FileNotFoundException 
*/
@Test
public void list() throws FileNotFoundException, IOException{
Path path = new Path("/tmp");
FileStatus[] fileList = fs.listStatus(path);
for (FileStatus file : fileList) {
System.out.println(file.getPath() + "-" + file.getLen() + "-" + file.getAccessTime());
}
}
/**
* 上传序列文件
* @throws IOException 
*/
@SuppressWarnings("deprecation")
@Test
public void uploadSequceFile() throws IOException{
Path path = new Path("/tmp/seq");
writer = SequenceFile.createWriter(fs, conf, path, Text.class, Text.class);
File f = new File("f:" + File.separator + "sequence");
for(File file : f.listFiles()){
writer.append(new Text(file.getName()), new Text(FileUtils.readFileToString(file)));
}
}
/**
* 下载序列文件
* @throws IOException 
*/
@Test
public void downloadSeq() throws IOException{
Path path = new Path("/tmp/seq");
Reader reader = new SequenceFile.Reader(fs, path, conf);
Text key = new Text();
Text val = new Text();
while(reader.next(key, val)){
System.out.println("文件名:" + key + ",文件内容:"+val);
}
}
/**
* 删除文件
* @throws IOException
*/
@Test
public void del() throws IOException{
Path path = new Path("/tmp/test");
if (fs.exists(path)) {
fs.delete(path);
}
}
}



猜你喜欢

转载自blog.csdn.net/ym01213/article/details/80034605