
HDFS命令行接口作为了解,在这里不再赘述
(二)JAVA API接口使用URL访问hdfs
1)怎么访问?
java.net.URL可以访问文件系统,但其默认支持http协议,不支持hdfs协议2)如何支持?
URL.setURLStreamHandlerFactory()方法中,添加hdfs协议对象FsUrlStreamHandlerFactory即可
即java.net.URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory())3)访问哪里?
hdfs文件系统的根目录是:hdfs://192.168.170.133:9000
public static void main(String[] args) throws Exception {
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
String url = "hdfs://192.168.170.133:9000/input/2.txt";
InputStream in = new URL(url).openStream();
IOUtils.copyBytes(in, System.out, 4096);
}
使用FileSystem读文件
1)hadoop的FileSystem类与hdfs进行交互
FileSystem是抽象类,不能直接new(),通过get()得到具体的实现类,即:
FileSystem fs = FileSystem.get();2)hadoop的Configuration类用来表示配置,即:
Configuration cfg = new Configuration();
cfg.set("fs.default.name", "hdfs://192.168.170.133:9000");3)hadoop的Path类用来表示hdfs中的路径,即:
Path p = new Path("hdfs:/input/2.txt");4)相关类
package com.qst.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public static void readFile() throws IOException {
// 1、定义配置对象
Configuration cfg = new Configuration();
// 2、设置配置对象的HDFS访问地址
cfg.set("fs.default.name", "hdfs://192.168.170.133:9000");
// 3、根据配置对象定义FileSystem实例
FileSystem fs = FileSystem.get(cfg);
// 4、定义文件路径
Path p = new Path("hdfs:/input/2.txt");
// 5、使用FileSystem实例打开文件
InputStream in = fs.open(p);
// 6、读取文件数据
IOUtils.copyBytes(in, System.out, 4096, false);
// 7、关闭文件
IOUtils.closeStream(in);
}
使用FileSystem写文件
public static void createFile() throws IOException {
Configuration cfg = new Configuration();
cfg.set("fs.default.name", "hdfs://192.168.170.133:9000");
FileSystem fs = FileSystem.get(cfg);
// 1、定义写入文件的路径
Path p = new Path("hdfs:/input/2.txt");
// 2、定义输出流
FSDataOutputStream out = fs.create(p);
// 3、写数据
out.write("你好!欢迎使用HDFS".getBytes());
// 4、关闭写
out.close();
// 5、关闭文件系统
fs.close();
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)