如何用JAVA程式碼操作HDFS

琉璃盒裡的暮色發表於2020-12-30

有時候我們不會直接上伺服器去操作Hadoop的HDFS,那麼下面我就為大家展示一下怎麼用JAVA程式碼操作Hadoop
pom如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wy</groupId>
    <artifactId>FOBJ</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>jdk.tools</groupId>
            <artifactId>jdk.tools</artifactId>
            <version>1.8</version>
            <scope>system</scope>
            <systemPath>E:/javajdk/lib/tools.jar</systemPath>
        </dependency>
    </dependencies>
</project>

具體操作起來其實很簡單程式碼如下:

package com.wy;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class HDFS {
    public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
        Configuration cfg =new Configuration();
        cfg.set("fs.defaultFS","hdfs://192.168.85.128:9000");

        FileSystem fs=FileSystem.get(new URI("hdfs://192.168.85.128:9000"),cfg,"root");
        fs.mkdirs(new Path("/cds"));
        fs.close();

    }

}

上面這個例子就是一個建立資料夾的例子,其他的操作同理,都是使用FileSystem的物件操作,大家用的時候就會發現方法名就是命令

相關文章