【问题标题】:HDFS File Encoding ConverterHDFS 文件编码转换器
【发布时间】:2021-01-21 13:13:57
【问题描述】:

我正在尝试将 HDFS 文件从 UTF-8 转换为 ISO-8859-1

我写了一个小的 Java 程序:

String theInputFileName="my-utf8-input-file.csv";
String theOutputFileName="my-iso8859-output-file.csv";
Charset inputCharset = StandardCharsets.UTF_8;
Charset outputCharset = StandardCharsets.ISO_8859_1;

try (
    final FSDataInputStream in = theFileSystem.open(new Path(theInputFileName)) ;
    final FSDataOutputStream out = theFileSystem.create(new Path(theOutputFileName))
)        
{
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in, inputCharset)))
    {
        String line;
        while ((line = reader.readLine()) != null)
        {
            out.write(line.getBytes(this.outputCharset));
            out.write(this.lineSeparator.getBytes(this.outputCharset));
        }
    }
} catch (IllegalArgumentException | IOException e)
{
    RddFileWriter.LOGGER.error(e, "Exception on file '%s'", theFileNameOutput);
}

这段代码使用Spark通过Hadoop集群执行(输出数据通常由RDD提供)

为了简化我的问题,我删除了 RDD/Datasets 部分以直接在 HDFS 文件上工作。

当我执行代码时:

  • Localy 在我的 DEV 计算机上:有效!,本地输出文件编码为 ISO-8859-1
  • EDGE 服务r 上:通过使用 HDFS 文件的 spark-submit 命令它可以工作! HDFS 输出文件编码为ISO-8859-1
  • Datanode via oozie 上:它不起作用 :-( :HDFS 输出文件编码为 UTF-8 而不是 ISO-8859-1

我不明白哪些属性(或其他)可能导致行为变化

版本:

  • Hadoop:v2.7.3
  • Spark : v2.2.0
  • Java:1.8

期待您的帮助。 提前致谢

【问题讨论】:

    标签: java apache-spark hadoop encoding hdfs


    【解决方案1】:

    终于找到了问题的根源。

    集群上的输入文件已损坏,整个文件没有恒定且一致的编码。

    每天都会汇总外部数据,最近编码已从 ISO 更改为 UTF8,恕不另行通知...

    简单地说:

    • 开头包含错误的转换 « é ê è » 而不是 « é ê è »
    • 结尾编码正确

    我们已经拆分、修复了编码并合并了数据以修复输入。

    最终代码运行良好。

    private void changeEncoding(
                final Path thePathInputFileName,final Path thePathOutputFileName,
                final Charset theInputCharset,  final Charset theOutputCharset,
                final String theLineSeparator
            ) {
        try (
            final FSDataInputStream in = this.fileSystem.open(thePathInputFileName);
            final FSDataOutputStream out = this.fileSystem.create(thePathOutputFileName);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(in, theInputCharset));
            final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, theOutputCharset));) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.write(theLineSeparator);
            }
            
        } catch (IllegalArgumentException | IOException e) {
            LOGGER.error(e, "Exception on file '%s'", theOutputFileName);
        }
    }
    

    停止你的研究! ;-)

    【讨论】:

      猜你喜欢
      • 2014-05-20
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2013-01-28
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多