解决:Spark DataFrame 读取 text(文本文件)乱码

本文档介绍了在Spark 2.4.3中遇到读取GBK编码的text文件导致乱码的问题,提供了两种解决方法,帮助读者解决DataFrame读取文本时的编码问题。

问题描述

   * Usage example:
   * {{{
   *   spark.read.text("/path/to/spark/README.md")
   * }}}

目前,Spark 2.4.3 读取 text(文本文件)的时候,只支持 UTF-8 编码,如果是其他编码(例如 GBK),返回的 DataFrame 会出现乱码。

解决方法1

      import org.apache.hadoop.io.{LongWritable, Text}
      import org.apache.hadoop.mapred.TextInputFormat
      import org.apache.spark.sql.Row
      import org.apache.spark.sql.types.{StringType, StructField, StructType}

      val spark = SparkSession.builder().getOrCreate()
      val sc = spark.sparkContext
      val encoding = "gbk"
      val filePath = "/path/to/spark/README.md"

      val rdd = sc.hadoopFile(filePath, classOf[TextInputFormat], classOf[LongWritable], classOf[Text]).map {
        case (_, t) => Row(new String(t.getBytes, 0, t.getLength, encoding))
      }
      val schema = StructType(Seq(StructField("value", StringType, nullable = true)))
      spark.createDataFrame(rdd, schema)

解决方法2

    import org.apache.spark.sql.functions.{col, decode}
    spark.read.format("text").load(filePath).select(decode(col("value"), encoding).as("value"))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值