1、创建一个项目
2、导入相关的Jar包
创建一个JUint测试类:
- package com.hdfs.testHdfs;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URI;
- import org.apache.commons.compress.utils.IOUtils;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.fs.FSDataInputStream;
- import org.apache.hadoop.fs.FSDataOutputStream;
- import org.apache.hadoop.fs.FileStatus;
- import org.apache.hadoop.fs.FileSystem;
- import org.apache.hadoop.fs.Path;
- import org.junit.Before;
- import org.junit.Test;
- /**
- *
- * Title: HDFSTest
- * Description: 测试HDFS
- * Company: http://blog.csdn.net/lu1005287365/
- * @author LYW
- * @date 2016年3月22日 19:35:07
- * @version 1.0
- */
- public class HDFSTest {
- // hdfs操作核心类
- FileSystem fileSystem = null;
- @Before
- public void setUp() throws Exception {
- URI uri = new URI("hdfs://hadoop:9000");
- Configuration configuration = new Configuration();
- /**
- * 这里Root如果不设置的话 将没有权限
- * 这里推荐使用root 不设置 可以在hdfs-site.xml配置 意思是关闭权限验证
- * 所有用户都可以操作
- * <property>
- <name>dfs.permissions</name>
- <value>false</value>
- </property>
- *
- */
- fileSystem = FileSystem.get(uri, configuration, "root");
- }
- @Test
- public void getPathAllFiles() throws Exception {
- // 递归方式取得指定目录下的文件信息
- FileStatus[] fileStatus = fileSystem.listStatus(new Path("/"));
- // 输出取得的文件权限和文件名称
- System.out.println("权限\t\t名称\t\t文件大小\t 修改时间");
- for (FileStatus fileStatus1 : fileStatus) {
- System.out.print(fileStatus1.getPermission() + "\t" + fileStatus1.getPath());
- System.out.print("\t"+fileStatus1.getLen());
- System.out.print("\t"+fileStatus1.getModificationTime());
- System.out.println();
- }
- }
- // 上传
- @Test
- public void put() throws Exception {
- // 如果同名是否覆盖
- boolean overwrite = true;
- // DFS文件输出流
- FSDataOutputStream outputStream = fileSystem.create(new Path("/测试文件.zip"), overwrite);
- // 本地输入流
- InputStream inputStream = new FileInputStream("D://测试文件.zip");
- // 使用工具类上传
- IOUtils.copy(inputStream, outputStream, 4096);
- }
- // 下载
- @Test
- public void get() throws Exception {
- // DFS文件输入流
- FSDataInputStream inputStreamOption = fileSystem.open(new Path("/测试文件.zip"));
- // 本地文件输出流
- OutputStream outputStream = new FileOutputStream("E:\\测试文件.zip");
- // 使用工具类下载
- IOUtils.copy(inputStreamOption, outputStream, 4096);
- }
- // 删除
- @Test
- public void del() throws Exception {
- fileSystem.delete(new Path("/input"), true);
- }
- }