美文网首页
科多大数据带你看:JAVA操作HDFS

科多大数据带你看:JAVA操作HDFS

作者: 大数据在说话 | 来源:发表于2017-07-27 17:40 被阅读0次

    1、导入代码文件

    pom.xml文件中加入以下内容

    org.apache.hadoop hadoop-common 2.6.5 org.apache.hadoop hadoop-hdfs 2.6.5

    java中操作HDFS

    1、公共区域

    FileSystem fs; @Before public void init() throws IOException, URISyntaxException{ String path="hdfs://ha1:9000"; fs=FileSystem.get(new URI(path), new Configuration()); }

    2、创建目录

    /** * 创建目录 * @throws IllegalArgumentException * @throws IOException */ @Test public void mkdir() throws IllegalArgumentException, IOException{ fs.mkdirs(new Path("/test4")); fs.close(); }

    注意事项:new Path中的/是必须要写的,可以同时创建多级目录 /keduox/aaa/bbb/ccc

    3、删除目录与删除文件一致

    /** * 删除文件 * @throws IllegalArgumentException * @throws IOException */ @Test public void deleteDir() throws IllegalArgumentException, IOException{ fs.delete(new Path("/test4"),true); fs.close(); } #### ==注意事项:/同样不能少,delete 默认为true,false时只能删除空的文件夹==

    4、创建文件

    /** * 创建一个文件 * @throws IllegalArgumentException * @throws IOException */ @Test public void createFile() throws IllegalArgumentException, IOException{ fs.createNewFile(new Path("/test.txt")); fs.close(); }

    5、下载文件到本地

    fs.copyToLocalFile(true,new Path("/test.txt"),new Path("d:/")); fs.close();

    注意事项:第一个true表示是“剪切”操作,没有或者false表示复制

    6、上传文件到HDFS

    @Test public void uploadFile() throws IllegalArgumentException, IOException{ fs.copyFromLocalFile(new Path("d:/test223/tttbb"), new Path("/test2.txt")); fs.close(); }

    7、将下载的文件传为流

    @Test public void fileToIo() throws IllegalArgumentException, IOException{ FSDataInputStream inputStream= fs.open(new Path("/jdk-8u111-linux-x64.tar.gz") ); IOUtils.copyBytes(inputStream,System.out,4096,false); }

    相关文章

      网友评论

          本文标题:科多大数据带你看:JAVA操作HDFS

          本文链接:https://www.haomeiwen.com/subject/ocftlxtx.html