设为首页 收藏本站
查看: 707|回复: 0

[经验分享] hadoop hdfs java api 文件操作类

[复制链接]

尚未签到

发表于 2016-12-9 09:37:47 | 显示全部楼层 |阅读模式
  


package test.hadoop.util;
import java.util.Iterator;
import java.util.Map.Entry;
import org.apache.commons.lang.exception.ExceptionUtils;
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.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import com.emar.adwiser.common.util.LogUtil;
import com.emar.adwiser.common.util.Logs;
/***
* HDFS 工具类
* @author zhaidw
*
*/
public class HDFSUtil {
private static Logs log = LogUtil.getLog(HDFSUtil.class);
public synchronized static FileSystem getFileSystem(String ip, int port) {
FileSystem fs = null;
String url = "hdfs://" + ip + ":" + String.valueOf(port);
Configuration config = new Configuration();
config.set("fs.default.name", url);
try {
fs = FileSystem.get(config);
} catch (Exception e) {
log.error("getFileSystem failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
return fs;
}
public synchronized static void listNode(FileSystem fs) {
DistributedFileSystem dfs = (DistributedFileSystem) fs;
try {
DatanodeInfo[] infos = dfs.getDataNodeStats();
for (DatanodeInfo node : infos) {
System.out.println("HostName: " + node.getHostName() + "/n"
+ node.getDatanodeReport());
System.out.println("--------------------------------");
}
} catch (Exception e) {
log.error("list node list failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
/**
* 打印系统配置
*
* @param fs
*/
public synchronized static void listConfig(FileSystem fs) {
Iterator<Entry<String, String>> entrys = fs.getConf().iterator();
while (entrys.hasNext()) {
Entry<String, String> item = entrys.next();
log.info(item.getKey() + ": " + item.getValue());
}
}
/**
* 创建目录和父目录
*
* @param fs
* @param dirName
*/
public synchronized static void mkdirs(FileSystem fs, String dirName) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
String dir = workDir + "/" + dirName;
Path src = new Path(dir);
// FsPermission p = FsPermission.getDefault();
boolean succ;
try {
succ = fs.mkdirs(src);
if (succ) {
log.info("create directory " + dir + " successed. ");
} else {
log.info("create directory " + dir + " failed. ");
}
} catch (Exception e) {
log.error("create directory " + dir + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
/**
* 删除目录和子目录
*
* @param fs
* @param dirName
*/
public synchronized static void rmdirs(FileSystem fs, String dirName) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
String dir = workDir + "/" + dirName;
Path src = new Path(dir);
boolean succ;
try {
succ = fs.delete(src, true);
if (succ) {
log.info("remove directory " + dir + " successed. ");
} else {
log.info("remove directory " + dir + " failed. ");
}
} catch (Exception e) {
log.error("remove directory " + dir + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
/**
* 上传目录或文件
*
* @param fs
* @param local
* @param remote
*/
public synchronized static void upload(FileSystem fs, String local,
String remote) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + remote);
Path src = new Path(local);
try {
fs.copyFromLocalFile(false, true, src, dst);
log.info("upload " + local + " to  " + remote + " successed. ");
} catch (Exception e) {
log.error("upload " + local + " to  " + remote + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
/**
* 下载目录或文件
*
* @param fs
* @param local
* @param remote
*/
public synchronized static void download(FileSystem fs, String local,
String remote) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + remote);
Path src = new Path(local);
try {
fs.copyToLocalFile(false, dst, src);
log.info("download from " + remote + " to  " + local
+ " successed. ");
} catch (Exception e) {
log.error("download from " + remote + " to  " + local + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
/**
* 字节数转换
*
* @param size
* @return
*/
public synchronized static String convertSize(long size) {
String result = String.valueOf(size);
if (size < 1024 * 1024) {
result = String.valueOf(size / 1024) + " KB";
} else if (size >= 1024 * 1024 && size < 1024 * 1024 * 1024) {
result = String.valueOf(size / 1024 / 1024) + " MB";
} else if (size >= 1024 * 1024 * 1024) {
result = String.valueOf(size / 1024 / 1024 / 1024) + " GB";
} else {
result = result + " B";
}
return result;
}
/**
* 遍历HDFS上的文件和目录
*
* @param fs
* @param path
*/
public synchronized static void listFile(FileSystem fs, String path) {
Path workDir = fs.getWorkingDirectory();
Path dst;
if (null == path || "".equals(path)) {
dst = new Path(workDir + "/" + path);
} else {
dst = new Path(path);
}
try {
String relativePath = "";
FileStatus[] fList = fs.listStatus(dst);
for (FileStatus f : fList) {
if (null != f) {
relativePath = new StringBuffer()
.append(f.getPath().getParent()).append("/")
.append(f.getPath().getName()).toString();
if (f.isDir()) {
listFile(fs, relativePath);
} else {
System.out.println(convertSize(f.getLen()) + "/t/t"
+ relativePath);
}
}
}
} catch (Exception e) {
log.error("list files of " + path + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
} finally {
}
}
public synchronized static void write(FileSystem fs, String path,
String data) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + path);
try {
FSDataOutputStream dos = fs.create(dst);
dos.writeUTF(data);
dos.close();
log.info("write content to " + path + " successed. ");
} catch (Exception e) {
log.error("write content to " + path + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
public synchronized static void append(FileSystem fs, String path,
String data) {
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + path);
try {
FSDataOutputStream dos = fs.append(dst);
dos.writeUTF(data);
dos.close();
log.info("append content to " + path + " successed. ");
} catch (Exception e) {
log.error("append content to " + path + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
}
public synchronized static String read(FileSystem fs, String path) {
String content = null;
// Path home = fs.getHomeDirectory();
Path workDir = fs.getWorkingDirectory();
Path dst = new Path(workDir + "/" + path);
try {
// reading
FSDataInputStream dis = fs.open(dst);
content = dis.readUTF();
dis.close();
log.info("read content from " + path + " successed. ");
} catch (Exception e) {
log.error("read content from " + path + " failed :"
+ ExceptionUtils.getFullStackTrace(e));
}
return content;
}
}

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-311789-1-1.html 上篇帖子: 运行hadoop时的一些技巧 下篇帖子: 自行实现Hadoop的多属性WritableComparable
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表