HDFS的文件系统输入输出流:
FSDataInputStream
FSDataOutputStream
本地文件系统输入输出流:
FileOutputStream
FileIntputStream
如果是上传:
创建HDFS文件系统的输入流
创建本地文件的输出流
直接对接即可
in = new FSDataInputStream(new Path(""))
out = new FileOutputStream(new File(""))
IOUtils.copy(out,in,4096,true)
案例演示
/**
* 相对那些封装好的方法而言的更底层一些的操作方式 上层那些MapReduce、Spark等运算框架,去 HDFS中获取数据的时候,就是调的这种底层的API
*/
public class StreamAccess {
FileSystem fs = null;
@Before
public void init() throws Exception {
Configuration conf = new Configuration();
System.setProperty("HADOOP_USER_NAME", "bigdata");
conf.set("fs.defaultFS", "hdfs://bigdata02:9000");
fs = FileSystem.get(conf);
// fs = FileSystem.get(new URI("hdfs://bigdata02:9000"), conf, "bigdata");
}
@Test
public void testDownLoadFileToLocal() throws IllegalArgumentException,IOException {
// 先获取一个文件的输入流----针对hdfs上的
FSDataInputStream in = fs.open(new Path("/jdk.tar.gz"));
// 再构造一个文件的输出流----针对本地的
FileOutputStream out = new FileOutputStream(new File("c:/jdk.tar.gz"));
// 再将输入流中数据传输到输出流
IOUtils.copyBytes(in, out, 4096, true);
}
@Test
public void testUploadByStream() throws Exception {
// hdfs文件的输出流
FSDataOutputStream fsout = fs.create(new Path("/aaa.txt"));
// 本地文件的输入流
FileInputStream fsin = new FileInputStream("c:/111.txt");
IOUtils.copyBytes(fsin, fsout, 4096, true);
}
/**
* hdfs支持随机定位进行文件读取,而且可以方便地读取指定长度 用于上层分布式运算框架并发处 理数据
*/
@Test
public void testRandomAccess() throws IllegalArgumentException, IOException {
// 先获取一个文件的输入流----针对hdfs上的
FSDataInputStream in = fs.open(new Path("/student.txt"));
// 可以将流的起始偏移量进行自定义
in.seek(22);
// 再构造一个文件的输出流----针对本地的
FileOutputStream out = new FileOutputStream(new
File("d:/student2.txt"));
IOUtils.copyBytes(in, out, 19L, true);
}
}