版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013490585/article/details/84492760
1.加入依赖
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.6.4</version>
</dependency>
2.文件上传到HDFS
/**
* @TODO 上传文件到HDFS
*/
@Test
public void testAddFileToHdfs() throws Exception{
// 要上传的文件所在的本地路径
Path src= new Path("F:\\staday-video.avi");
// 要上传到hdfs的目标路径
Path dst= new Path("/test_dir/");
if(!fs.exists(dst))fs.mkdirs(dst);
try {
fs.copyFromLocalFile(src, dst);
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.从HDFS中下载文件到本地
/**
* @TODO 从HDFS中下载文件到本地
*/
@Test
public void testDownloadFileToLocal() throws Exception{
fs.copyToLocalFile(
false,//是否删除原文件
new Path("/test_dir/staday-video.avi"),//源路径
new Path("e:/"),//目标路径
true //目标路径是否本地文件系统
);
fs.close();
}
4.创建目录、删除目录/文件、重命名 目录/文件
@Test
public void testMkdirAndDeleteAndRename() throws IllegalArgumentException, IOException {
// 创建目录
fs.mkdirs(new Path("/test_new/a1/b1"));
// 删除文件夹 ,如果是非空文件夹,参数2必须给值true
fs.delete(new Path("/aaa"), true);
// 重命名文件或文件夹
fs.rename(new Path("/test_new"), new Path("/test_n"));
}
5.查看目录信息,只显示文件
/**
* 查看目录信息,只显示文件
*
* @throws IOException
* @throws IllegalArgumentException
* @throws FileNotFoundException
*/
@Test
public void testListFiles() throws FileNotFoundException, IllegalArgumentException, IOException {
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
while (listFiles.hasNext()) {
LocatedFileStatus fileStatus = listFiles.next();
System.out.println(fileStatus.getPath().getName());
System.out.println(fileStatus.getBlockSize());
System.out.println(fileStatus.getPermission());
System.out.println(fileStatus.getLen());
BlockLocation[] blockLocations = fileStatus.getBlockLocations();
for (BlockLocation bl : blockLocations) {
System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset());
String[] hosts = bl.getHosts();
for (String host : hosts) {
System.out.println(host);
}
}
System.out.println("--------------打印的分割线--------------");
}
}
6.上述例子的demo工程下载