Hadoop HDFS (3) JAVA訪问HDFS
这个类是用来跟Hadoop的文件系统进行交互的。尽管我们这里主要是针对HDFS。可是我们还是应该让我们的代码仅仅使用抽象类FileSystem。这样我们的代码就能够跟不论什么一个Hadoop的文件系统交互了。在写測试代码时,我们能够用本地文件系统測试,部署时使用HDFS。仅仅需配置一下,不须要改动代码了。
用Hadoop URL来读取HDFS里的文件
InputStream in = null;
try {
in = new URL("hdfs://host/path").openStream();
//操作输入流in。能够读取到文件的内容
} finally {
IOUtils.closeStream(in);
}
import java.io.InputStream;
import java.net.URL;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.apache.hadoop.io.IOUtils; public class URLCat {
static {
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
public static void main(String[] args) throws Exception {
InputStream in = null;
try {
in = new URL(args[0]).openStream();
IOUtils.copyBytes(in, System.out, 4096, false);
} finally {
IOUtils.closeStream(in);
}
}
}
用FileSystem(org.apache.hadoop.fs.FileSystem)类来读取HDFS里的文件
public static FileSystem get(Configuration conf) throws IOException;
public static FileSystem get(URI uri, Configuration conf) throws IOException;
public static FileSystem get(final URI uri, final Configuration conf, final String user) throws IOException, InterruptedException;
public static LocalFileSystem getLocal(Configuration conf) throws IOException;
public FSDataInputStream open(Path f) throws IOException;
public abstract FSDataInputStream open(Path f, int bufferSize) throws IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class FileSystemCat {
public static void main(String[] args) throws Exception {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
//System.out.println(fs.getClass().getName()); //这里能够看到得到的实例是DistributedFileSystem,由于core-site.xml里配的是hdfs
FSDataInputStream in = null;
try {
in = fs.open(new Path(uri));
IOUtils.copyBytes(in, System.out, 4096, false);
} finally {
IOUtils.closeStream(in);
}
}
}
in.seek(0);
IOUtils.copyBytes(in, System.out, 4096, false);
public int read(long position, byte[] buffer, int offset, int length) throws IOException;
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException;
public void readFully(long position, byte[] buffer) throws IOException;
用FileSystem类来向HDFS里写文件
public FSDataOutputStream create(Path f) throws IOException;
public FSDataOutputStream create(Path f, Progressable progress) throws IOException;
public interface Progressable {
public void progress();
}
public FSDataOutputStream append(Path f) throws IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable; public class FileCopyWithProgress {
public static void main(String[] args) throws Exception {
String localSrc = args[0];
String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(dst), conf);
OutputStream out = fs.create(new Path(dst), new Progressable() {
@Override
public void progress() {
System.out.print(".");
// try {
// Thread.sleep(1000);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
});
IOUtils.copyBytes(in, out, 4096, true);
System.out.println();
System.out.println("end.");
}
}
public long getPos() throws IOException;
创建文件夹
查询文件元信息:FileStatus(org.apache.hadoop.fs.FileStatus)
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ShowFileStatusTest {
private static final String SYSPROP_KEY = "test.build.data";
/** MiniDFSCluster类在hadoop-hdfs-2.4.1-tests.jar中,是一个专门用于測试的in-process HDFS集群 */
private MiniDFSCluster cluster;
private FileSystem fs;
@Before
public void setUp() throws IOException {
Configuration conf = new Configuration();
String sysprop = System.getProperty(SYSPROP_KEY);
if (sysprop == null) {
System.setProperty(SYSPROP_KEY, "/tmp");
}
cluster = new MiniDFSCluster(conf, 1, true, null);
fs = cluster.getFileSystem();
OutputStream out = fs.create(new Path("/dir/file"));
out.write("content".getBytes("UTF-8"));
out.close();
}
@After
public void tearDown() throws IOException {
if (fs != null) {
fs.close();
}
if (cluster != null) {
cluster.shutdown();
}
}
@Test(expected = FileNotFoundException.class)
public void throwsFileNotFoundForNonExistentFile() throws IOException {
fs.getFileStatus(new Path("no-such-file"));
}
@Test
public void fileStatusForFile() throws IOException {
Path file = new Path("/dir/file");
FileStatus stat = fs.getFileStatus(file); assertThat(stat.getPath().toUri().getPath(), is("/dir/file"));
assertThat(stat.isDirectory(), is(false));
assertThat(stat.getLen(), is(7L));
assertTrue(stat.getModificationTime() <= System.currentTimeMillis());
assertThat(stat.getReplication(), is((short)1));
assertThat(stat.getBlockSize(), is(64 * 1024 * 1024L));
assertThat(stat.getOwner(), is("norris"));
assertThat(stat.getGroup(), is("supergroup"));
assertThat(stat.getPermission().toString(), is("rw-r--r--"));
}
@Test
public void fileStatusForDirectory() throws IOException {
Path dir = new Path("/dir");
FileStatus stat = fs.getFileStatus(dir);
assertThat(stat.getPath().toUri().getPath(), is("/dir"));
assertThat(stat.isDirectory(), is(true));
assertThat(stat.getLen(), is(0L));
assertTrue(stat.getModificationTime() <= System.currentTimeMillis());
assertThat(stat.getReplication(), is((short)0));
assertThat(stat.getBlockSize(), is(0L));
assertThat(stat.getOwner(), is("norris"));
assertThat(stat.getGroup(), is("supergroup"));
assertThat(stat.getPermission().toString(), is("rwxr-xr-x"));
}
}
Hadoop HDFS (3) JAVA訪问HDFS的更多相关文章
- Hadoop HDFS (3) JAVA訪问HDFS之二 文件分布式读写策略
先把上节未完毕的部分补全,再剖析一下HDFS读写文件的内部原理 列举文件 FileSystem(org.apache.hadoop.fs.FileSystem)的listStatus()方法能够列出一 ...
- Hadoop-2.6.0上的C的API訪问HDFS
在通过Hadoop-2.6.0的C的API訪问HDFS的时候,编译和执行出现了不少问题,花费了几天的时间,上网查了好多的资料,最终还是把问题给攻克了 參考文献:http://m.blog.csdn.n ...
- HDFS简单介绍及用C语言訪问HDFS接口操作实践
一.概述 近年来,大数据技术如火如荼,怎样存储海量数据也成了当今的热点和难点问题,而HDFS分布式文件系统作为Hadoop项目的分布式存储基础,也为HBASE提供数据持久化功能,它在大数据项目中有很广 ...
- JAVA訪问URL
JAVA訪问URL: package Test; import java.io.BufferedReader; import java.io.IOException; import java.io.I ...
- Java 訪问权限控制:你真的了解 protected keyword吗?
摘要: 在一个类的内部,其成员(包含成员变量和成员方法)是否能被其它类所訪问,取决于该成员的修饰词:而一个类是否能被其它类所訪问,取决于该类的修饰词.Java的类成员訪问权限修饰词有四类:privat ...
- Cassandra数据库Java訪问
针对的时Cassandra 2.0 数据库 Java本地client訪问Cassandra,首先建立Javaproject,使用Maven进行管理. 引入依赖: <dependency> ...
- Hadoop学习(2)-java客户端操作hdfs及secondarynode作用
首先要在windows下解压一个windows版本的hadoop 然后在配置他的环境变量,同时要把hadoop的share目录下的hadoop下的相关jar包拷贝到esclipe 然后Build Pa ...
- HDFS的java接口——简化HDFS文件系统操作
今天闲来无事,于是把HDFS的基本操作用java写出简化程序出来给大家一些小小帮助! package com.quanttech; import org.apache.hadoop.conf.Conf ...
- 三国武将查询系统 //Java 訪问 数据库
import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event ...
随机推荐
- SGU 170.Particles
Solution: 这其实是道很简单的题. 只要从一端开始,以‘+’或‘-’,任意一种开始找,找到与目标串最近的相同字符的距离就是需要交换的次数 ...
- javascript——可以判断值的类型的函数
function classof(o){ return Object.prototype.toString.call(0).slice(8,-1); } Function.prototype.getN ...
- 用jQuery实现瀑布流效果学习笔记
jQuery一直没系统的学,只知道是js库,封装了好多js函数,方便了开发.以前做过一个原生的图片网站瀑布流效果,超级麻烦,这次用了jQuery方法,瞬间代码浓缩了,只有56行js代码.神奇的让我来把 ...
- node应用通过multer模块实现文件上传
multer用于处理文件上传的nodejs中间件,主要跟express框架搭配使用,只支持表单MIME编码为multipart/form-data类型的数据请求. 如果要处理其他编码的表单数据可以通过 ...
- Win8.1 64bit安装Genymotion模拟器
其实安装并不复杂,只要环境正常,此事并不难.但估计最坏的情况都被我撞上了,才折腾了差不多一天的 那我有哪些环境不正常呢? 破解了系统主题 Device Install Service服务未启动 下面来 ...
- JDK和JRE的区别?
很多朋友可能跟我一样,已经使用JAVA开发很久了,可是对JDK,JRE,JVM这三者的联系与区别,一直都是模模糊糊的. 今天特写此文,来整理下三者的关系. JDK : Java Development ...
- 省队集训Day3 tree
[题目描述] RHL 有一天看到 lmc 在玩一个游戏. “愚蠢的人类哟,what are you doing”,RHL 说. “我在玩一个游戏.现在这里有一个有 n 个结点的有根树,其中有 m 个叶 ...
- hadoop job执行完的统计信息
Total committed heap usage (bytes)= Physical memory (bytes) snapshot= Virtual memory (bytes) snapsho ...
- Tomcat8 配置Oracle11g数据源
1:context.xml <Resource name="jdbcoracle" auth="Container" type="javax.s ...
- "Ray, Pass me the dishes!"
uvaLive3938:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&pag ...