package org.jeecg.sy.java;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import java.io.IOException;

public class HDFSUtils {
    private static FileSystem fileSystem;

    // 初始化HDFS文件系统
    public static void initFileSystem(String hdfsUri) throws IOException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", hdfsUri);
        fileSystem = FileSystem.get(conf);
    }

    // 写入数据到HDFS文件
    public static void writeToHDFS(String path, String data) throws IOException {
        Path filePath = new Path(path);
        FSDataOutputStream outputStream = fileSystem.create(filePath, true);
        outputStream.writeUTF(data);
        outputStream.close();
    }

    // 从HDFS文件读取数据
    public static String readFromHDFS(String path) throws IOException {
        Path filePath = new Path(path);
        FSDataInputStream inputStream = fileSystem.open(filePath);
        String data = inputStream.readUTF();
        inputStream.close();
        return data;
    }

    // 删除HDFS文件
    public static boolean deleteFromHDFS(String path) throws IOException {
        Path filePath = new Path(path);
        return fileSystem.delete(filePath, true);
    }

    // 关闭文件系统连接
    public static void closeFileSystem() throws IOException {
        if (fileSystem != null) {
            fileSystem.close();
        }
    }
}

