操作HDFS文件,约有以下两种方法
(1)shell,这个相信大家基本都会;
(2)Java API 的操作
这次主要记录下Java API操作HDFS文件的相关测试
环境:IDEA+JDK10.0.1,虚拟机centos
版本:hadoop2.6.0-cdh5.7.0, junit 4.11,maven3.0
事先要在pom.xml中添加相关依赖,并指定一个仓库
测试代码如下:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.net.URI;
/**
* Hadoop HDFS 的Java API 操作
* */
public class HDFSApp {
//操作HDFS文件系统,注意选择hadoop相关的
FileSystem fileSystem =null;
//配置类
Configuration configuration=null;
//定义路径
public static final String HDFS_PASH="hdfs://192.168.199.128:8020";
//**创建HDFS目录
@Test //单元测试
public void mkdir()throws Exception{
fileSystem.mkdirs(new Path("/hafsapi/test"));
}
//**创建文件
@Test
public void creat()throws Exception{
FSDataOutputStream out = fileSystem.create(new Path("/hafsapi/test/a.txt"));
out.write("hello hadoop".getBytes());
out.flush();
//关闭流
out.close();
}
//**查看HDFS文件的内容
@Test
public void cat()throws Exception{
FSDataInputStream in = fileSystem.open(new Path("/hafsapi/test/a.txt"));
IOUtils.copyBytes(in,System.out,1024);
//关闭流
in.close();
}
//**文件重命名
@Test
public void rename()throws Exception{
Path oldPath =new Path("/hafsapi/test/a.txt");
Path newPath =new Path("/hafsapi/test/abc.txt");
fileSystem.rename(oldPath,newPath);
}
//**从本地(指的是win下安装盘,而非虚拟机)拷贝文件到HDFS上面,上传文件
@Test
public void copyFromLocalFile()throws Exception{
Path localPath = new Path("/JavaWork/data/h.txt");
Path hdfsPath = new Path("/h.txt");
fileSystem.copyFromLocalFile(localPath,hdfsPath);
}
//**下载HDFS文件到本地
@Test
public void copyToLocalFile()throws Exception{
Path localPath = new Path("/JavaWork/data/h.txt");
Path hdfsPath = new Path("/hi.txt");
fileSystem.copyToLocalFile(false,hdfsPath, localPath,true);
}
//**查看某个目录下的所有文件
@Test
public void listFiles()throws Exception{
FileStatus[] fileStatuses=fileSystem.listStatus(new Path("/"));
for(FileStatus fileStatus:fileStatuses){
//判断是文件夹还是文件
String isDr=fileStatus.isDirectory()?"文件夹":"文件";
//有几个副本,即副本系数
short replication= fileStatus.getReplication();
//文件大小
long fileLen=fileStatus.getLen();
//打印出路径
String path=fileStatus.getPath().toString();
System.out.println(isDr+"\t"+replication+"\t"+fileLen+"\t"+path);
}
}
//删除某个文件
@Test
public void dele()throws Exception{
fileSystem.delete(new Path("/h,txt"));
}
//准备环境
@Before //在单元测试之前执行
public void setUp()throws Exception{
System.out.println("HDFSApp setUp");
configuration=new Configuration();
fileSystem = FileSystem.get(new URI(HDFS_PASH),configuration, "hadoop");
}
//释放资源
@After //在单元测试之后执行
public void tearDown()throws Exception{
configuration=null;
fileSystem =null;
System.out.println("HDFSApp tearDown");
}
}
注意:
在查看某个路径下的所有文件时,
如果是通过hadoop shell的方式put上去的,采用配置的xml文件中的副本系数1;如果是通过Java API 上传上去,因为在本地没有手工设置副本系数,所有采用的时hadoop副本系数3。