首页 技术 正文
技术 2022年11月16日
0 收藏 893 点赞 2,452 浏览 1134 个字
1. 在生产环境下,很多文件是GBK编码格式的,而SPARK 常用的textFile方法默认是写死了读UTF-8格式的文件,其他格式文件会显示乱码
用如下代码实现读取GBK文件的方法

import org.apache.hadoop.io.{LongWritable, Text}
import org.apache.hadoop.mapred.TextInputFormat
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}object GBKtoUtf8 { def main(args: Array[String]) {
val sparkConf = new SparkConf().setMaster("local").setAppName("spark sql test")
val sc = new SparkContext(sparkConf)
//textFile 默认只支持Utf-8格式,这种方法都到的是乱码
   //这里用的是文件夹路径,也可以指定到具体文件
sc.textFile("/Users/hduser/Downloads/gbk").foreach(println)
//通过封装后的方法读取GBK文件,并讲每一行数据以字符串格式返回(RDD[String])
transfer(sc,"/Users/hduser/Downloads/gbk").foreach(println)
} def transfer(sc:SparkContext,path:String):RDD[String]={
sc.hadoopFile(path,classOf[TextInputFormat],classOf[LongWritable],classOf[Text],1)
.map(p => new String(p._2.getBytes, 0, p._2.getLength, "GBK"))
}}
 
2. 构建测试文件
如果你用的是Mac OS,可以按照我如下步骤操作(http://www.cnblogs.com/bonnienote/p/6139545.html),打开Bash cd /Users/hduser/Downloads/gbkecho "Bonnie 大数据|学姐笔记 果果学姐" > test_utf8.txt转换命令iconv -f UTF-8 -t GBK test_utf8.txt > test_gbk.txt在IDEA运行上述程序,结果如下Bonnie ����ݣ�ѧ��ʼ� ���ѧ��
Bonnie 大数据|学姐笔记 果果学姐可以看到第一次调用textFile时,显示文件为乱码
而第二次调用GBK文件的读取方法是,显示文件正常
 
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,955
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,775