【问题标题】:How to Save Dataframe as Text File using User Defined File Name in Spark Java如何在 Spark Java 中使用用户定义的文件名将数据框保存为文本文件
【发布时间】:2020-04-26 14:01:37
【问题描述】:

我正在尝试将数据框保存到特定位置。

successDF.toJavaRDD().saveAsTextFile(successFilePath);

这里,successFilePath 是:/hdfs/tmp/20200102/04.dat

我需要将文件名保存为 04.dat 的数据,其中 20200102 和 04 作为参数传入

但该过程会创建多个文件,如下所示:

Folder: /hdfs/tmp/20200102/04.dat
Files:
._SUCCESS.crc
.part-00000.crc
_SUCCESS
part-00000

我的要求是,输出文件应该在/hdfs/tmp/20200102中创建,并且在文件夹下应该只有1个文件,文件名为:04.dat

注意我正在使用 Spark Java

请推荐

【问题讨论】:

  • 如果你可以只用一个减速器“SPARK”运行作业,你会得到它
  • 不清楚为什么需要 1 个文件。这不是应该使用 Hadoop 的方式。如果您需要一个文件,您可以使用 getmerge CLI 下载它
  • 文件只有一行。它就像一个只有一行数据的触摸文件
  • 那你就不需要 RDD 了。只需使用 HDFS API 创建文件。
  • @Vladislav,您能否指定您指的是哪个 HDFS API。仅供参考,这只是更大 Spark 工作的一部分,我需要在 hdfs 中生成一个带有一行数据的触摸文件

标签: java dataframe apache-spark filesystems hdfs


【解决方案1】:

您可以在不使用 Spark 的情况下在 HDFS 上创建文件:

使用HDFS API

import java.io.IOException;

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

public class HDFSFileWrite {


public static void main(String[] args) {
    Configuration conf = new Configuration();
    try {
        FileSystem fs = FileSystem.get(conf);
        // Hadoop DFS Path - Input & Output file
        Path inFile = new Path(args[0]);
        Path outFile = new Path(args[1]);
        // Verification
        if (!fs.exists(inFile)) {
            System.out.println("Input file not found");
            throw new IOException("Input file not found");
        }
        if (fs.exists(outFile)) {
            System.out.println("Output file already exists");
            throw new IOException("Output file already exists");
        }

        // open and read from file
        FSDataInputStream in = fs.open(inFile);
        // Create file to write
        FSDataOutputStream out = fs.create(outFile);

        byte buffer[] = new byte[256];
        try {
            int bytesRead = 0;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
              }
        } catch (IOException e) {
            System.out.println("Error while copying file");
        } finally {
            in.close();
            out.close();
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多