Java操作hdfs的API接口
package com.zhouxy;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
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.*;
public class hdfsUtils {
static FileSystem fs = null;
/***
* hdfs参数初始化
*
* @throws Exception
*/
public static void hdfsInit() throws Exception {
// TODO Auto-generated method stub
/*
* 构造一个配置参数对象,设置一个参数:我们要访问的hdfs的URI
* 从而FileSystem.get()方法就知道应该是去构造一个访问hdfs文件系统的客户端,以及hdfs的访问地址 new
* Configuration();的时候,它就会去加载jar包中的hdfs-default.xml
* 然后再加载classpath下的hdfs-site.xml
*/
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
/**
* 参数优先级: 1、客户端代码中设置的值 2、classpath下的用户自定义配置文件 3、然后是服务器的默认配置
*/
conf.set("dfs.replication", "3");
// 获取一个hdfs的访问客户端,根据参数,这个实例应该是DistributedFileSystem的实例
fs = FileSystem.get(conf);
// 如果这样去获取,那conf里面就可以不要配"fs.defaultFS"参数,而且,这个客户端的身份标识已经是hadoop用户
// fs = FileSystem.get(new URI("hdfs://localhost:9000"), conf,
// "localhost");
}
/***
* 向hdfs上传文件
*
* @param src
* : 上传文件的本地路径
* @param dst
* :上传到hdfs的目标路径
* @throws Exception
*/
public static void uploadToHdfs(String src, String dst) throws Exception {
fs.copyFromLocalFile(new Path(src), new Path(dst));
fs.close();
}
/***
* 从hdfs中复制文件到本地文件系统
*
* @param src
* : hdfs的目标路径
* @param dst
* :本地文件系统的路径
* @throws Exception
*/
public static void downLoadFileToLocal(String src, String dst) throws Exception {
fs.copyToLocalFile(new Path(src), new Path(dst));
fs.close();
}
/***
* 创建文件夹
*
* @param f
* : hdfs中创建文件夹的路径
* @throws Exception
*/
public static void mkdir(String f) throws Exception {
// 创建目录
fs.mkdirs(new Path(f));
}
/***
* 删除文件夹
*
* @param f
* : hdfs中要删除文件夹的路径
* @param b
* : hdfs中如果是非空文件夹, 参数2必须给值true
* @throws Exception
*/
public static void delete(String f, boolean b) throws Exception {
fs.delete(new Path(f), true);
}
/***
* 重命名文件或文件夹
*
* @param src : hdfs 中源文件的名称
* @param dst : hdfs 中重命名后的文件的名称
* @throws Exception
*/
public static void rename(String src, String dst) throws Exception {
fs.rename(new Path(src), new Path(dst));
}
/***
* 查看目录信息,只显示文件
* @param f
* @throws Exception
*/
public static void listFiles(String f) throws Exception{
RemoteIterator listFiles = fs.listFiles(new Path(f), true);
while(listFiles.hasNext())
{
LocatedFileStatus tmp = listFiles.next();
}
}
/***
* 查看文件及文件夹信息
* @param f
* @throws Exception
*/
public static void listAll(String f) throws Exception
{
FileStatus[] listStatus = fs.listStatus(new Path(f));
String flag = "d-- ";
for (FileStatus fstatus : listStatus) {
if (fstatus.isFile()) flag = "f-- ";
System.out.println(flag + fstatus.getPath().getName());
}
}
}