1.Java代码操作HDFS需要用到Jar包和Java类

Jar包:

hadoop-common-2.6.0.jar和hadoop-hdfs-2.6.0.jar

Java类:

java.net.URL
org.apache.hadoop.fs.FsUrlStreamHandlerFactory
java.net.URI
org.apache.hadoop.conf.Configuration
org.apache.hadoop.fs.FileSystem
org.apache.hadoop.fs.Path
org.apache.hadoop.io.IOUtils

2.读文件的过程
客户端(client)用FileSystem的open()函数打开文件,DistributedFileSystem用RPC调用名称节点,得到文件的数据块信息。对于每一个数据块,名称节点返回保存数据块的数据节点的地址。
DistributedFileSystem返回FSDataInputStream给客户端,用来读取数据。
客户端调用stream的read()函数开始读取数据。DFSInputStream连接保存此文件第一个数据块的最近的数据节点。
Data从数据节点读到客户端(client),当此数据块读取完毕时,DFSInputStream关闭和此数据节点的连接,然后连接此文件下一个数据块的最近的数据节点。
当客户端读取完毕数据的时候,调用FSDataInputStream的close函数。
在读取数据的过程中,如果客户端在与数据节点通信出现错误,则尝试连接包含此数据块的下一个数据节点。失败的数据节点将被记录,以后不再连接。

3.上代码:

写文件 create
读取文件 open
删除文件delete
创建目录 mkdirs
删除文件或目录 delete
列出目录的内容 listStatus
显示文件系统的目录和文件的元数据信息 getFileStatus

ReadHdfsFile.java

 import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL; 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.FsUrlStreamHandlerFactory; import java.net.URI;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils; public class ReadHdfsFile {
//让Java程序识别HDFS的URL
static{
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
static String fileSystemUri = "hdfs://192.168.211.130:9000"; public static void main(String[] args) throws Exception {
String fileHdfsPath = "hdfs://192.168.211.130:9000/user/root/metafile2.xml";
String fileHdfsPath2 = "hdfs://192.168.211.130:9000/user/root/metafile.xml";
String fileHdfsPath3 = "hdfs://192.168.211.130:9000/user/root/metafile3.xml";
String fileHdfsPath4 = "hdfs://192.168.211.130:9000/user/root/testCopy.txt";
String localFilePath = "D://test.txt";
String folderHdfsPath = "hdfs://192.168.211.130:9000/bbb";
//mkdir(folderHdfsPath);
//readFilePrint(fileHdfsPath);
//judgeFileOrFolder(fileHdfsPath2);
//rmdir(folderHdfsPath);
readFileAndCopy(localFilePath,fileHdfsPath4);
readFilePrint(fileHdfsPath4); }
/**
* 打印hdfs上指定的文本文件
* @param fileHdfsPath
* @throws URISyntaxException
* @throws IOException
*/
private static void readFilePrint(String fileHdfsPath) throws URISyntaxException, IOException {
FileSystem fileSystem = getFileSystem(fileSystemUri);
FSDataInputStream hdfsInputStream = fileSystem.open(new Path(fileHdfsPath)); byte[] ioBuffer = new byte[1024];
int readLen = hdfsInputStream.read(ioBuffer);
while(readLen != -1){
System.out.write(ioBuffer, 0, readLen);
readLen = hdfsInputStream.read(ioBuffer);
}
hdfsInputStream.close();
fileSystem.close();
}
/**
* 得到hdfs文件系统对象
* @param fileSystemUri
* @return
* @throws URISyntaxException
* @throws IOException
*/
private static FileSystem getFileSystem(String fileSystemUri) throws URISyntaxException,
IOException {
Configuration conf = new Configuration();
conf.set("fs.hdfs.impl",org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
URI uri = new URI(fileSystemUri);
final FileSystem fileSystem = FileSystem.get(uri, conf);
return fileSystem;
} /**
* 读取文件,调用fileSystem的open(path)
* @throws Exception
*/
private static void readFileAndCopy(String sourceFileHdfsPath,String targetFileHdfsPath) throws Exception {
FileSystem fileSystem = getFileSystem(fileSystemUri);
//获得这段代码运行的时所处的系统(如果在windows上运行就是Windows本地操作系统)
Configuration configuration=new Configuration();
FileSystem locationFileSystem=FileSystem.getLocal(configuration); FSDataInputStream inputStream = null;
FSDataOutputStream outputStream = null;
//输出路径
Path outPath = new Path(targetFileHdfsPath);
if(sourceFileHdfsPath.startsWith("hdfs://")){
inputStream = fileSystem.open(new Path(sourceFileHdfsPath));
}else{
inputStream = locationFileSystem.open(new Path(sourceFileHdfsPath));
}
//打开输出流
if(!(fileSystem.exists(outPath))){
outputStream = fileSystem.create(outPath);
}else {
outputStream = fileSystem.append(outPath);
} IOUtils.copyBytes(inputStream, outputStream, 1024, false);
IOUtils.closeStream(inputStream);
}
/*
各个参数所代表的含义:
in: 是FSDataInputStream类的对象,是有关读取文件的类,也就是所谓“输入流”
out:是FSDataOutputStream类的对象,是有关文件写入的类,也就是“输出流”
4096表示用来拷贝的buffer大小(buffer是缓冲区)
false表明拷贝完成后我们并不关闭拷贝源可拷贝目的地
上面inputStream和outputStream都是通过FileSystem类
fileSystem和fs都是FileSystem类的对象,path和block都是路径Path类的对象
然后IOUtils.copyBytes(in, out, 4096, false)方法实现了文件合并及上传至hdfs上
*/ /**
* 创建目录,调用fileSystem的mkdirs(path)
* @throws Exception
*/
private static void mkdir(String folderHdfsPath) throws Exception {
FileSystem fileSystem = getFileSystem(fileSystemUri);
fileSystem.mkdirs(new Path(folderHdfsPath));
} /**
* 删除目录,调用fileSystem的deleteOnExit(path)
* @throws Exception
*/
private static void rmdir(String folderHdfsPath) throws Exception {
FileSystem fileSystem = getFileSystem(fileSystemUri);
fileSystem.delete(new Path(folderHdfsPath));
} /**
* 遍历目录,使用FileSystem的listStatus(path) 如果要查看file状态,使用FileStatus对象
* @throws Exception
*/
private static void judgeFileOrFolder(String fileHdfsPath) throws Exception {
FileSystem fileSystem = getFileSystem(fileSystemUri);
FileStatus[] listStatus = fileSystem.listStatus(new Path(fileHdfsPath));
for (FileStatus fileStatus : listStatus) {
String isDir = fileStatus.isDir() ? "目录" : "文件";
String name = fileStatus.getPath().toString();
System.out.println(isDir + " " + name);
}
} }

如果代码中报AccessControlException: Permission denied:

在conf/hdfs-site.xml增加
<property>
<name>dfs.permissions</name>
<value>false</value>
</property>
中文字符集:/etc/sysconfig/i18n

Java代码操作HDFS测试类的更多相关文章

  1. Java代码操作HDFS(在/user/root/下面創建目錄)

    1.创建HDFS目录并打成jar包 package Hdfs; import java.io.IOException; import java.net.URI; import org.apache.h ...

  2. 大数据之路week07--day01(HDFS学习,Java代码操作HDFS,将HDFS文件内容存入到Mysql)

    一.HDFS概述 数据量越来越多,在一个操作系统管辖的范围存不下了,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,因此迫切需要一种系统来管理多台机器上的文件,这就是分布式文件管理系统 ...

  3. Java代码操作HDFS

    package com.hy.hdfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; imp ...

  4. 从 Java 代码逆向工程生成 UML 类图和序列图

    from:http://blog.itpub.net/14780914/viewspace-588975/ 本文面向于那些软件架构师,设计师和开发人员,他们想使用 IBM® Rational® Sof ...

  5. Java代码操作zookeeper

    .personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...

  6. Myeclipse中把java代码导成UML类图

    Myeclipse中把java代码导成UML类图 1.右键点击项目名称,选择New-------àUML2 Model 2.给类图命名 3.导成类图 1)如果要把整个项目导成类图,则把整个项目拖到类图 ...

  7. 使用Java API操作HDFS文件系统

    使用Junit封装HFDS import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org ...

  8. 使用java代码操作Redis

    1导入pom.xml依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis ...

  9. java代码操作Redis

    1.导入需要的pom依赖 <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEn ...

随机推荐

  1. i2c_client 几种实例化方法

    http://blog.csdn.net/lugandong/article/details/48092397

  2. java使用filter设置跨域访问

    import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...

  3. HDU 2057 十六进制加减法

    http://acm.hdu.edu.cn/showproblem.php?pid=2057   水题,%I64X 长整形十六进制输入输出     #include<stdio.h> in ...

  4. CentOS 5.8下快速搭建FTP服务器

    学习安装和配置vsftpd: 实验环境:CentOS 5.8 x86_64 测试环境关掉防火墙和selinux. service iptables stop setenforce 0 1.安装vsft ...

  5. Alpha冲刺 - (10/10)

    Part.1 开篇 队名:彳艮彳亍团队 组长博客:戳我进入 作业博客:班级博客本次作业的链接 Part.2 成员汇报 组员1(组长)柯奇豪 过去两天完成了哪些任务 本人负责的模块(共享编辑)的前端代码 ...

  6. dropzone 上传插件

    dropzone dropzone.js是一个可预览的上传文件工具,不依赖任何框架(如jQuery),且具有可定制化.实现文件拖拽上传,提供AJAX异步上传功能. 1. html文件 dropzone ...

  7. 用命令行上传本地代码到GitHub

    有两种方式上传,ssh和https,ssh老是报错=.=我用的是https 先下载git   https://git-scm.com/downloads 在代码的文件夹的同级目录中邮件打开git ba ...

  8. libgdx游戏中的中文字体工具类

    // ---------全局Font------------ static FreeTypeFontGenerator Generator; static BitmapFont Font; stati ...

  9. 1.虚拟机中安装ubuntu

    1.VMware安装很简单,全部默认安装即可. 2.安装完VMware之后,打开VMware,点击创建虚拟机 典型安装易出问题,所以这里选择自定义安装 安装过程选项配置如下 处理器数,核数,内存都可以 ...

  10. 在.net中使用ETW事件的方法

    直到.net4.5,才有了比较便利的操作ETW的方法. 本文介绍的方法主要来源于Microsoft.Diagnostics.Tracing.TraceEvent官方资料库. 准备 (1)需要用到类:M ...