HDFS的文件操作

本篇文章主要讲述Hadoop下hdfs的Java客户端操作,服务器端系统为Centos7,客户端系统为Windows,实现文件的上传,下载,创建,删除,查看功能。

一、启动HDFS

在Centos下启动hdfs,我这里直接启动全部节点。

start-all.sh

查看所需节点是否已启动

 jps

 

 如以上节点在运行,则说明启动成功。

二、创建项目并引入hdfs依赖

我这里直接把所需的hdoop所需jar包进行了一个封装,直接创建一个library。

 将hadoop/share/hadoop/hdfs下的核心包及lib文件夹下的jar包直接导入,再导入hadoop/share/hadoop/common下的核心包及lib文件夹下的jar包。

 

 三、客户端程序编写

package hadoop01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.junit.Before;
import org.junit.Test;

public class HdfsUtil {

	FileSystem fs = null;

	/*
	 * 初始化
	 */
	@Before
	public void init() throws Exception{
		//解析hadoop的配置文件
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://192.168.2.100:9000/");

		//获得hdfs的文件操作对象,因为是在Windows下运行,默认是使用window的administrator账户进行操作,所以需要将用户改为Centos下的账户,eric是我在Centos下的账户
		fs = FileSystem.get(new URI("hdfs://192.168.2.100:9000/"), conf, "eric");
	}

	/*
	 * 文件上传(第一种方式)
	 */
	@Test
	public void upload() throws IOException {

		Path dst = new Path("hdfs://192.168.2.100:9000/aa/test.txt");
		FSDataOutputStream os = fs.create(dst);

		FileInputStream is = new FileInputStream("D://test.txt");

		IOUtils.copy(is, os);

	}

	/*
	 * 文件上传(第二种方式)
	 */
	@Test
	public void upload2() throws IllegalArgumentException, IOException {
		fs.copyFromLocalFile(new Path("D://test.txt"), new Path("hdfs://192.168.2.100:9000/aa/test2.txt"));
	}
	
	/*
	 * 文件下载
	 */
	@Test
	public void download() throws IllegalArgumentException, IOException{
		fs.copyToLocalFile(new Path("hdfs://192.168.2.100:9000/aa/test2.txt"), new Path("D://test2.txt"));
	}
	
	/*
	 * 创建文件夹
	 */
	@Test
	public void mkdir() throws IllegalArgumentException, IOException{
		fs.mkdirs(new Path("/aaa/bbb/ccc"));
	}
	
	/*
	 * 删除文件或文件夹
	 */
	@Test
	public void rm() throws IllegalArgumentException, IOException{
		fs.delete(new Path("/aaa"),true);
	}
	
	/*
	 * 查看文件或文件夹
	 */
	@Test
	public void listFiles() throws FileNotFoundException, IllegalArgumentException, IOException{
		RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
		while(listFiles.hasNext()){
			LocatedFileStatus file = listFiles.next();
			Path path = file.getPath();
			String name = path.getName();
			System.out.println(name);
		}
	}

}
发布了125 篇原创文章 · 获赞 68 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42109746/article/details/100703756