FSDataOutputStream.writeUTF(String)写入文本乱码或空行详解

在使用IDEA中使用 FSDataOutputStream.writeUTF(String) 向hdfs中写文件时如果把文件下载到本地,打开会看到如上图一样类似的乱码或有空行的情况,代码如下:

public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {

    // 获得文件系统
    Configuration configuration = new Configuration();
    // 配置在集群上运行
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop101:9000"), configuration, "ml");

    if (fs.exists(new Path("/xxy/Demo01/hdfs/test.csv"))) {
        fs.delete(new Path("/xxy/Demo01/hdfs/test.csv"));
    }
    FSDataOutputStream fos = fs.create(new Path("/xxy/Demo01/hdfs/test.csv"));

    HashMap map = new HashMap();
    map.put("您好", 7.3);
    map.put("啊", 7.3);
    map.put("哈哈哈", 7.3);

    for (String s :
            map.keySet()) {
        String str = s+","+map.get(s).toString();
        fos.writeUTF(str); // UTF每写一行,都好在前面记录上这一行的字符数
    }

    fos.flush();
    IOUtils.closeStream(fos);
    fs.close();

    System.out.println("over");
}

其实这里面看到的乱码或空行,是在每次调用WriteUTF()函数时,会在你要写的内容前面增加本次写入文本的字符长度,如下图红色标注(本例子实际写了三行,就不一一标注出来了),所以在用文本编辑器打开时会看到类似乱码或空行的情况。

 

你可能感兴趣的:(大数据)