如何通过java程序访问hdfs

目录

配置依赖:

编写java代码:

1. uploadToHDFS

2. downloadFromHDFS

3. createHDFSDirectory

4. deleteFromHDFS

5.getHDFSFileMetadata

6. listHDFSFiles


配置依赖:

使用 Maven 进行项目管理,在 pom.xml 文件中添加以下依赖:

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.3.1</version>
        </dependency>

编写java代码:

提供了基本的 HDFS 文件系统操作功能,涵盖了文件上传、下载、目录创建、删除、获取元数据以及列出文件和目录的功能。通过这些方法,可以在 Java 程序中方便地操作和管理 HDFS 中的数据和文件系统。

主类,调用各个方法

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

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        // 创建配置对象
        Configuration conf = new Configuration();
        // 设置HDFS的URI
        conf.set("fs.defaultFS", "hdfs://localhost:8020"); //在本地启动的Hadoop
        // 创建FileSystem对象
        FileSystem fs = FileSystem.get(conf);

        // 从HDFS中删除文件或目录
        //HDFSOperations.deleteFromHDFS(fs,"/test2",false);
        // 在HDFS中创建目录
        //HDFSOperations.createHDFSDirectory(fs,"/test2");
        // 获取HDFS文件或目录的元数据
        //HDFSOperations.getHDFSFileMetadata(fs,"/");
        // 列出HDFS目录中的文件和子目录
        //HDFSOperations.listHDFSFiles(fs,"/test2");
        // 从HDFS下载文件到本地
        //HDFSOperations.downloadFromHDFS(fs,"/test2","Desktop/test2");
        // 上传本地文件到HDFS
        //HDFSOperations.uploadToHDFS(fs,"Desktop/Book1.csv","/test2");
        // 获取HDFS根目录
        Path root = new Path("/");
        FileStatus[] status = fs.listStatus(root);

        // 输出根目录下的文件和目录
        for (FileStatus file : status) {
            System.out.println(file.getPath().toString());
        }

        // 关闭FileSystem对象
        fs.close();
    }
}

操作类,编写各操作方法

import org.apache.hadoop.fs.*;
import java.io.IOException;

public class HDFSOperations {



    // 上传本地文件到HDFS
    public static void uploadToHDFS(FileSystem fs,String srcPath, String destPath) throws IOException {
        fs.copyFromLocalFile(new Path(srcPath), new Path(destPath));
    }

    // 从HDFS下载文件到本地
    public static void downloadFromHDFS(FileSystem fs,String srcPath, String destPath) throws IOException {
        fs.copyToLocalFile(new Path(srcPath), new Path(destPath));
    }

    // 在HDFS中创建目录
    public static void createHDFSDirectory(FileSystem fs,String dirPath) throws IOException {
        fs.mkdirs(new Path(dirPath));
    }

    // 从HDFS中删除文件或目录
    public static void deleteFromHDFS(FileSystem fs,String path, boolean recursive) throws IOException {
        fs.delete(new Path(path), recursive);
    }

    // 获取HDFS文件或目录的元数据
    public static void getHDFSFileMetadata(FileSystem fs,String filePath) throws IOException {
        FileStatus status = fs.getFileStatus(new Path(filePath));
        System.out.println("File path: " + status.getPath());
        System.out.println("File size: " + status.getLen());
        System.out.println("File owner: " + status.getOwner());
        System.out.println("File permission: " + status.getPermission());
    }

    // 列出HDFS目录中的文件和子目录
    public static void listHDFSFiles(FileSystem fs,String dirPath) throws IOException {
        FileStatus[] statuses = fs.listStatus(new Path(dirPath));
        for (FileStatus status : statuses) {
            System.out.println("Path: " + status.getPath());
            System.out.println("Is directory: " + status.isDirectory());
            System.out.println("Owner: " + status.getOwner());
            System.out.println("Permission: " + status.getPermission());
            System.out.println("Size: " + status.getLen());
            System.out.println("---------");
        }
    }

}

代码分析:

1. uploadToHDFS

public static void uploadToHDFS(FileSystem fs, String srcPath, String destPath) throws IOException {
    fs.copyFromLocalFile(new Path(srcPath), new Path(destPath));
}
  • 功能:将本地文件上传到 HDFS 中。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • srcPath:本地文件路径。
    • destPath:HDFS 中的目标路径。
  • 说明:使用 copyFromLocalFile 方法将本地文件复制到 HDFS 中指定的目标路径。

2. downloadFromHDFS

public static void downloadFromHDFS(FileSystem fs, String srcPath, String destPath) throws IOException {
    fs.copyToLocalFile(new Path(srcPath), new Path(destPath));
}
  • 功能:从 HDFS 下载文件到本地。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • srcPath:HDFS 中的文件路径。
    • destPath:本地目标路径。
  • 说明:使用 copyToLocalFile 方法将 HDFS 中的文件复制到本地文件系统中指定的目标路径。

3. createHDFSDirectory

public static void createHDFSDirectory(FileSystem fs, String dirPath) throws IOException {
    fs.mkdirs(new Path(dirPath));
}
  • 功能:在 HDFS 中创建目录。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • dirPath:要在 HDFS 中创建的目录路径。
  • 说明:使用 mkdirs 方法在 HDFS 中创建指定路径的目录。如果上级目录不存在,也会一并创建。

4. deleteFromHDFS

public static void deleteFromHDFS(FileSystem fs, String path, boolean recursive) throws IOException {
    fs.delete(new Path(path), recursive);
}
  • 功能:从 HDFS 中删除文件或目录。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • path:要删除的文件或目录路径。
    • recursive:布尔值,表示是否递归删除(对于目录而言)。
  • 说明:使用 delete 方法删除指定路径的文件或目录。如果 recursive 参数为 true,并且 path 是目录,则会递归删除整个目录及其内容。

5.getHDFSFileMetadata

public static void getHDFSFileMetadata(FileSystem fs, String filePath) throws IOException {
    FileStatus status = fs.getFileStatus(new Path(filePath));
    System.out.println("File path: " + status.getPath());
    System.out.println("File size: " + status.getLen());
    System.out.println("File owner: " + status.getOwner());
    System.out.println("File permission: " + status.getPermission());
}
  • 功能:获取 HDFS 中文件或目录的元数据信息。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • filePath:HDFS 中文件或目录的路径。
  • 说明:使用 getFileStatus 方法获取指定路径的 FileStatus 对象,然后打印其路径、大小、所有者和权限等信息。

6. listHDFSFiles

public static void listHDFSFiles(FileSystem fs, String dirPath) throws IOException {
    FileStatus[] statuses = fs.listStatus(new Path(dirPath));
    for (FileStatus status : statuses) {
        System.out.println("Path: " + status.getPath());
        System.out.println("Is directory: " + status.isDirectory());
        System.out.println("Owner: " + status.getOwner());
        System.out.println("Permission: " + status.getPermission());
        System.out.println("Size: " + status.getLen());
        System.out.println("---------");
    }
}
  • 功能:列出 HDFS 目录中的文件和子目录,并打印它们的元数据信息。
  • 参数
    • fsFileSystem 对象,用于与 HDFS 交互。
    • dirPath:HDFS 中要列出的目录路径。
  • 说明:使用 listStatus 方法获取指定目录下所有文件和子目录的 FileStatus 数组,然后逐个遍历打印每个文件或目录的路径、是否为目录、所有者、权限和大小等信息。

怎么访问远程Hadoop服务

1,修改URL:

fs.defaultFS 的值修改为远程服务器的 HDFS 地址,格式为 hdfs://hostname:port

conf.set("fs.defaultFS", "hdfs://remote-hostname:8020");

2,安全认证:

如果在尝试连接HDFS时需要认证信息,那么需要通过UserGroupInformation 类的 createRemoteUser 方法创建远程用户对象,以模拟远程用户的身份。其中Hadoop依赖版本要改为“3.3.sdi-118.1-SNAPSHOT”,“3.3.1”中UserGroupInformation 类中createRemoteUser 方法参数没有(String user,String rpcPassword)。

user和rpcPassword对应身份信息。

conf.set("hadoop.security.authentication", "kerberos");
        // 设置远程用户的安全上下文
        UserGroupInformation remoteUser = UserGroupInformation.createRemoteUser(user,rpcPassword);
        remoteUser.addCredentials(new Credentials()); // 添加你的票证信息

        // 使用远程用户执行操作
        remoteUser.doAs((PrivilegedExceptionAction<Void>) () -> {
            // 这里可以放置需要以远程用户身份执行的代码,如访问 HDFS 文件系统等操作
            // FileSystem fs = FileSystem.get(conf);
            // Path path = new Path("/path/to/remote/directory");
            // fs.listFiles(path, false);
            return null;
        });

3,进行远程操作:

doAs 方法中,可以以远程用户的身份执行代码块,这样可以确保在 Hadoop 集群中以正确的权限和身份执行操作。

代码示例:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;
import java.security.PrivilegedExceptionAction;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建配置对象
        Configuration conf = new Configuration();
        // 设置HDFS的URI
        conf.set("fs.defaultFS", "hdfs://remote-hostname:8020");
        conf.set("hadoop.security.authentication", "kerberos");

        // 设置远程用户的安全上下文
        UserGroupInformation remoteUser = UserGroupInformation.createRemoteUser(user,rpcPassword);

        // 使用远程用户执行操作
        remoteUser.doAs((PrivilegedExceptionAction<Void>) () -> {

            // 创建FileSystem对象
            FileSystem fs = FileSystem.get(conf);

            Path root = new Path("/");
            FileStatus[] status = fs.listStatus(root);

            // 输出根目录下的文件和目录
            for (FileStatus file : status) {
                System.out.println(file.getPath().toString());
            }

            // 关闭FileSystem对象
            fs.close();

            return null;
        });


    }
}

  • 25
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

达芬奇要当程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值