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 ...
随机推荐
- js 强制转换
强制转换为布尔类型: <script> var text =Boolean(0) //=>以下转换的类型都为false text = Boolean(0.0) text = Bool ...
- “layout_”下划线开头的属性
观看幕课网的视频的收获 “layout_”下划线开头的属性都是交给父容器去处理的属性,如: android:layout_width="match_parent" android: ...
- SQL SERVER 2008 nvarchar 转换 deciaml 失败(nvarchar to decimal)
转换数据发生 消息 8115,级别 16,状态 6,第 1 行 将 nvarchar 转换为数据类型 numeric 时出现算术溢出错误. nvarchar 是带很长小数,直接转换成decimal 失 ...
- bzoj1662: [Usaco2006 Nov]Round Numbers 圆环数
Description 正如你所知,奶牛们没有手指以至于不能玩“石头剪刀布”来任意地决定例如谁先挤奶的顺序.她们甚至也不能通过仍硬币的方式. 所以她们通过"round number" ...
- 纯Html+Ajax和JSP两者的优缺点
我对jsp和ajax 一直比较困惑, jsp动态网页技术,在服务器端执行,能在网页中显示数据这是一种方式 .另一种方式是我打开一个网页(html),加载完成之后,使用js,ajax访问网络得到json ...
- 搭建一个 简易的php版 todolist
我记得以前使用 wunderlist 但是国外..后来用了半年. 挺方便的.但是.后来慢慢忘了这工具存在 缺少了todolist.效率折半.. so.我搭建了个简单的todolist. :mytin ...
- 最新game
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h&g ...
- 【Java】ArrayList和LinkedList的区别
一般大家都知道ArrayList和LinkedList的大致区别: 1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构. 2.对于随机访问 ...
- Android 判断wifi和4G网络是否开启
public boolean isWifiAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) g ...
- Keepalived实现Redis Failover
一.环境说明 操作系统版本:RHEL 5.4_64 redis版本:2.8.17 keepalived版本:1.1.15 master:10.142.130.81 slave: 10.142.130 ...