Hadoop(二)——HDFS的 IO 流操作

    技术2022-07-11  134

    API操作的HDFS系统都是框架封装好的,可以采用 I/O 流的方式实现数据的上传和下载。

    HDFS文件上传

    1、需求:将本地D盘上的honglou.txt文件上传到HDFS根目录 2、代码块

    @Test public void putFileToHDFS() throws IOException,InterruptedException,URISyntaxException{ //1、获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop101:9000"),configuration,"root"); //2、创建输入流 FileInputStream fis = new FileInputStream(new Path("d:/honglou.txt")); //3、获取输出流 FSDataOutputStream fos = fs.create(new Path("/honglou.txt")); //4、流对拷 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); }

    HDFS文件下载

    1、从HDFS下载honglou.txt文件到d盘 代码:

    @Test public void getFileFromHDFS() throws IOException,InterruptedException,URISyntaxException{ //1、获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop101:9000"),configuration,"root"); //2、获取入流 FSDataInputStream fis = fs.open(new Path("/honglou.txt")); //3、获取输出流 FileOutputStream fos = new FileOutputStream(new File("d:/honglou.txt")); //4、流对拷 IOUtils.copyBytes(fis,fos,configuration); IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); }

    定位文件读取

    1、需求:分块读取HDFS上的大文件,比如根目录下的、hadoop-2.7.2.tar.gz 2、代码如下 (1)下载第一块

    @Test public void readFileSeek1() throws IOException,InterruptedException,URISyntaxException{ //获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop101:9000"),configuration,"root"); //获取输入流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); //获取输出流 FileOutputStream fos = new FileOutputStream(new File("d:/hadoop-2.7.2.tar.gz.part1")); //流拷贝 byte[] buf = new byte[1024]; for(int i =0;i<1024*128;i++){ fis.read(buf); fos.write(buf); } //关闭资源 IOUtils.closeStream(fis); IOUtils.closeStream(fos); fs.close(); }

    2、下载第二块

    @Test public void readFileSeek2() throws IOException,InterruptedException,URISyntaxException{ //获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop101:9000"),configuration,"root"); //打开数据流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); //定位输入数据位置 fis.seek(1024*1024*128); //创建输出流 FileOutputStream fos = new FileOutputStream(new File("d:/hadoop-2.7.2.tar.gz.part2")); //流对拷 IOUtils.copyBytes(fis,fos,configuration); //关闭资源 IOUtils.closeStream(fis); IOUtils.closeStream(fos); }
    Processed: 0.018, SQL: 9