JAVA操作HDFS案例

Jar包引入,pom.xml:

    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-hdfs</artifactId>
      <version>2.8.0</version>
    </dependency>

將本地文件上傳到hdfs服務器:

    /**
     * 上傳文件到hdfs上
     */
    @Test
    public void upload() throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hzq:9000");
        FileSystem fs = FileSystem.get(conf);
        fs.copyFromLocalFile(new Path("/home/hzq/jdk1.8.tar.gz"),new Path("/demo"));
    }
解析:

      在開發中我沒有引入“core-site.xml”配置文件,所以在本地調用時使用conf進行配置“conf.set("fs.defaultFS","hdfs://hzq:9000");“,下面雷同。

將hdfs上文件下載到本地:

    /**
     * 將hdfs上文件下載到本地
     */
    @Test
    public void download() throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hzq:9000");
        FileSystem fs = FileSystem.newInstance(conf);
        fs.copyToLocalFile(new Path("/java/jdk1.8.tar.gz"),new Path("/home/hzq/"));
    }
刪除hdfs上指定文件:

    /**
     * 刪除hdfs上的文件
     * @throws IOException
     */
    @Test
    public void removeFile() throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hzq:9000");
        FileSystem fs = FileSystem.newInstance(conf);
        fs.delete(new Path("/demo/jdk1.8.tar.gz"),true);
    }
在hdfs上創建文件夾:
    /**
     * 在hdfs更目錄下面創建test1文件夾
     * @throws IOException
     */
    @Test
    public void mkdir() throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hzq:9000");
        FileSystem fs = FileSystem.newInstance(conf);
        fs.mkdirs(new Path("/test1"));
    }
列出hdfs上所有的文件或文件夾:

 @Test
    public void listFiles() throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hzq:9000");
        FileSystem fs = FileSystem.newInstance(conf);
        // true 表示遞歸查找  false 不進行遞歸查找
        RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(new Path("/"), true);
        while (iterator.hasNext()){
            LocatedFileStatus next = iterator.next();
            System.out.println(next.getPath());
        }
        System.out.println("----------------------------------------------------------");
        FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
        for (int i = 0; i < fileStatuses.length; i++) {
            FileStatus fileStatus = fileStatuses[i];
            System.out.println(fileStatus.getPath());
        }
    }
運行結果:

                                     

結果分析:

       “listFiles“列出的是hdfs上所有文件的路徑,不包括文件夾。根據你的設置,支持遞歸查找。

       ”listStatus“列出的是所有的文件和文件夾,不支持遞歸查找。如許遞歸,需要自己實現。

總結:熟能生巧,加油!!!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章