Linux下Hadoop hdfs Java API使用
0 前言
1 步骤
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>maven</groupId>
- <artifactId>maven</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>maven</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-minicluster</artifactId>
- <version>2.5.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-client</artifactId>
- <version>2.5.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-assemblies</artifactId>
- <version>2.5.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-maven-plugins</artifactId>
- <version>2.5.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-common</artifactId>
- <version>2.5.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-hdfs</artifactId>
- <version>2.5.1</version>
- </dependency>
- </dependencies>
- </project>
然后等待eclipse maven自动下载依赖的包。等啊等就好了,下一步是配置jvm运行的参数,因为运行的时候需要本地的库所以必须配置下。我的Hadoop是放在/home/hadoop-master/hadoop-2.5.1下的。
- -Djava.library.path=/home/hadoop-master/hadoop-2.5.1/lib/native
因为hadoop2.5.1自己已经编译好了本地库所以不用在编译一次了(这就是用新不用旧的原因,自己编译太费事儿了。。。。到此一切OK
2 测试代码
- package maven.maven;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.util.Date;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.fs.BlockLocation;
- 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.DFSClient.*;
- import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
- public class HadoopFSOperations {
- private static Configuration conf = new Configuration();
- private static final String HADOOP_URL="hdfs://192.168.190.129:9000";
- private static FileSystem fs;
- private static DistributedFileSystem hdfs;
- static {
- try {
- FileSystem.setDefaultUri(conf, HADOOP_URL);
- fs = FileSystem.get(conf);
- hdfs = (DistributedFileSystem)fs;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 列出所有DataNode的名字信息
- */
- public void listDataNodeInfo() {
- try {
- DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();
- String[] names = new String[dataNodeStats.length];
- System.out.println("List of all the datanode in the HDFS cluster:");
- for (int i=0;i<names.length;i++) {
- names[i] = dataNodeStats[i].getHostName();
- System.out.println(names[i]);
- }
- System.out.println(hdfs.getUri().toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 查看文件是否存在
- */
- public void checkFileExist() {
- try {
- Path a= hdfs.getHomeDirectory();
- System.out.println("main path:"+a.toString());
- Path f = new Path("/user/xxx/input01/");
- boolean exist = fs.exists(f);
- System.out.println("Whether exist of this file:"+exist);
- //删除文件
- // if (exist) {
- // boolean isDeleted = hdfs.delete(f, false);
- // if(isDeleted) {
- // System.out.println("Delete success");
- // }
- // }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- *创建文件到HDFS系统上
- */
- public void createFile() {
- try {
- Path f = new Path("/user/xxx/input02/file01");
- System.out.println("Create and Write :"+f.getName()+" to hdfs");
- FSDataOutputStream os = fs.create(f, true);
- Writer out = new OutputStreamWriter(os, "utf-8");//以UTF-8格式写入文件,不乱码
- out.write("你好 good job");
- out.close();
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 读取本地文件到HDFS系统<br>
- * 请保证文件格式一直是UTF-8,从本地->HDFS
- */
- public void copyFileToHDFS() {
- try {
- Path f = new Path("/user/xxx/input02/file01");
- File file = new File("E:\\hadoopTest\\temporary.txt");
- FileInputStream is = new FileInputStream(file);
- InputStreamReader isr = new InputStreamReader(is, "utf-8");
- BufferedReader br = new BufferedReader(isr);
- FSDataOutputStream os = fs.create(f, true);
- Writer out = new OutputStreamWriter(os, "utf-8");
- String str = "";
- while((str=br.readLine()) != null) {
- out.write(str+"\n");
- }
- br.close();
- isr.close();
- is.close();
- out.close();
- os.close();
- System.out.println("Write content of file "+file.getName()+" to hdfs file "+f.getName()+" success");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 取得文件块所在的位置..
- */
- public void getLocation() {
- try {
- Path f = new Path("/user/xxx/input02/file01");
- FileStatus fileStatus = fs.getFileStatus(f);
- BlockLocation[] blkLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
- for (BlockLocation currentLocation : blkLocations) {
- String[] hosts = currentLocation.getHosts();
- for (String host : hosts) {
- System.out.println(host);
- }
- }
- //取得最后修改时间
- long modifyTime = fileStatus.getModificationTime();
- Date d = new Date(modifyTime);
- System.out.println(d);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 读取hdfs中的文件内容
- */
- public void readFileFromHdfs() {
- try {
- Path f = new Path("/user/xxx/input02/file01");
- FSDataInputStream dis = fs.open(f);
- InputStreamReader isr = new InputStreamReader(dis, "utf-8");
- BufferedReader br = new BufferedReader(isr);
- String str = "";
- while ((str = br.readLine()) !=null) {
- System.out.println(str);
- }
- br.close();
- isr.close();
- dis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * list all file/directory
- * @param args
- * @throws IOException
- * @throws IllegalArgumentException
- * @throws FileNotFoundException
- */
- public void listFileStatus(String path) throws FileNotFoundException, IllegalArgumentException, IOException {
- FileStatus fileStatus[]=fs.listStatus(new Path(path));
- int listlength=fileStatus.length;
- for (int i=0 ;i<listlength ;i++){
- if (fileStatus[i].isDirectory() == false) {
- System.out.println("filename:"
- + fileStatus[i].getPath().getName() + "\tsize:"
- + fileStatus[i].getLen());
- } else {
- String newpath = fileStatus[i].getPath().toString();
- listFileStatus(newpath);
- }
- }
- }
- public static void main(String[] args) {
- HadoopFSOperations a = new HadoopFSOperations();
- a.listDataNodeInfo();
- // a.checkFileExist();
- // a.createFile();
- // a.copyFileToHDFS();
- // a.getLocation();
- // a.readFileFromHdfs();
- try {
- a.listFileStatus(HADOOP_URL+"/user");
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
因为我的hadoop是在192.168.190.129上的所以private static final String HADOOP_URL="hdfs://192.168.190.129:9000";,请酌情修改。搞定跑起来,就能看到下面的结果
- List of all the datanode in the HDFS cluster:
- hadoopslaver0
- hadoopslaver2
- hadoopslaver1
- hdfs://192.168.190.129:9000
- filename:TrustCom2015_CFP.pdf size:290401
- filename:jd.PNG size:16647
可以看到 三个datanode hadoopslaver0,1,2 以及/user下事先放好的文件。小实验成功
3 总结
Linux下Hadoop hdfs Java API使用相关推荐
- hadoop hdfs (java api)
简单介绍使用java控制hdfs文件系统 一.注意namenode端访问权限,修改hdfs-site.xml文件或修改文件目录权限 本次采用修改hdfs-site.xml用于测试,在configura ...
- HDFS Java API 操作
文章目录 HDFS Java API操作 零.启动hadoop 一.HDFS常见类接口与方法 1.hdfs 常见类与接口 2.FileSystem 的常用方法 二.Java 创建Hadoop项目 1. ...
- ubuntu linux下解决“no java virtual machine was found after searching the following locations:”的方法
ubuntu linux下解决"no java virtual machine was found after searching the following locations:" ...
- Linux -- 基于zookeeper的java api(二)
Linux -- 基于zookeeper的java api(二) 写一个关于基于集群的zookeeper的自定义实现HA 基于客户端和监控器:使用监控的方法查看每个注册过的节点的状态来做出操作. Wa ...
- 离线计算系统之HDFS Java API
HDFS的java操作:hdfs在生产应用中主要是客户端的开发,其核心步骤是从hdfs提供的api中构造一个HDFS的访问客户端对象,然后通过该客户端对象操作(增删改查)HDFS上的文件 一.搭建开发 ...
- 【hadoop2.6.0】利用Hadoop的 Java API
Hadoop2.6.0的所有Java API都在 http://hadoop.apache.org/docs/r2.6.0/api/overview-summary.html 里. 下面实现一个利用J ...
- 分布式文件系统—HDFS—Java API操作
原文作者:jiangw-Tony 原文地址:HDFS基础使用 hdfs 在生产应用中主要是客户端的开发,其核心步骤是从 hdfs 提供的 api 中构造一个 HDFS的访问客户端对象,然后通过该客户端 ...
- hdfs java api读写
如果想在win下下载hdfs的文件,需要安装hadoop的win版,因为写入磁盘的程序对linux和win编译结果不同 下载地址是: https://github.com/cdarlint/winut ...
- java mapreduce api_Hadoop实战-初级部分 之 Hadoop MapReduce JAVA API
精品视频课程推荐 Java数据结构和算法精讲版 本课程专注于数据结构和算法的内容,使用Java来进行代码示例,不空洞的讲解概念和理论,重点放在代码的实现和示例上. 从零开始.全面系统.成体系的讲解数据 ...
最新文章
- codeforces #310 div1 C
- 数学分析高等代数考研试题荟萃[更新至2017年10月1日]
- Drop Down Menu
- python中rfind函数_Python rfind()方法
- 【LeetCode】0136. 只出现一次的数字
- boost::spirit模块实现罗马数字解析器的测试程序
- mysql数据表案例_mysql中库和表的简单操作案例
- 仿百度文库实现文档在线预览
- sqlserver 触发器语法
- ERP基础知识100问题,值得收藏
- python下载pandas库_Python中的pandas库
- Unity Burst 用户指南
- 开发在线投票系统过程遇到的问题
- 如何给PDF中的内容添加下划线
- 大数据变现的九种商业模式
- 数字电路的一些基本知识
- pr系统兼容性报告不支持视频驱动程序有什么影响?怎么解决?
- VHDL硬件描述语言(六)VHDL案例
- 图解两部委DSM数据安全管理认证
- 使用手机可以在线拍照、翻译图片文字吗?
热门文章
- 【Java 虚拟机原理】JDK 体系结构 | Java 源码运行原理 | Java 虚拟机内存
- 【设计模式】策略模式 ( 简介 | 适用场景 | 优缺点 | 代码示例 )
- 【商务智能】数据预处理
- 【错误记录】Android 应用 release 打包报错处理 ( 关闭语法检查 | 日志处理 | release 配置 )
- 【组合数学】排列组合 ( 排列组合示例 )
- 2019年六月刷题列表
- 没有人比你更在乎你的未来--李开复
- windows上安装gcc/g++环境(MinGW,msys64等)
- Docker配置mysql互为主从
- hdu 1700 (圆的内接三角形 要周长最大)