fsdataoutputstream.writeutf()在hdfs上的数据开头添加额外的字符如何避免这些额外的数据?

qojgxg4l  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(327)

我尝试的是将hdfs上包含xml数据的序列文件转换为hdfs上的.xml文件。
在谷歌上搜索,找到了下面的代码。我根据需要做了修改,下面是代码。。

public class SeqFileWriterCls {
    public static void main(String args[]) throws Exception {
        System.out.println("Reading Sequence File");
        Path path = new Path("seq_file_path/seq_file.seq");
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        SequenceFile.Writer writer = null;
        SequenceFile.Reader reader = null;
        FSDataOutputStream fwriter = null;
        OutputStream fowriter = null;
        try {
            reader = new SequenceFile.Reader(fs, path, conf);
            //writer = new SequenceFile.Writer(fs, conf,out_path,Text.class,Text.class);
            Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);

            Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);

            while (reader.next(key, value)) {
            //i am just editing the path in such a way that key will be my filename and data in it will be the value
                Path out_path = new Path(""+key);
                String string_path = out_path.toString();
                String clear_path=string_path.substring(string_path.lastIndexOf("/")+1);

                Path finalout_path = new Path("path"+clear_path);
                System.out.println("the final path is "+finalout_path);
                fwriter = fs.create(finalout_path);
                fwriter.writeUTF(value.toString());
                fwriter.close();
                FSDataInputStream in = fs.open(finalout_path);
                String s = in.readUTF();
                System.out.println("file has: -" + s);
                //fowriter = fs.create(finalout_path); 
                //fowriter.write(value.toString());
                System.out.println(key + "  <===>  :" + value.toString());
                System.exit(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeStream(reader);
            fs.close();
        }

}

我使用“fsdataoutputstream”将数据写入hdfs,使用的方法是“writeutf”。问题是,当我写入hdfs文件时,数据的开头会出现一些额外的字符。但是当我打印数据时,我看不到额外的字符。
我试过使用writechars(),但即使是taht也不起作用。
有什么办法可以避免吗??或者有没有其他方法将数据写入hdfs???
请帮忙。。。

bakd9h0s

bakd9h0s1#

世界的javadoc writeUTF(String str) 方法如下:
以独立于机器的方式使用修改的utf-8编码将字符串写入底层输出流。首先,两个字节被写入到输出流中,就好像是通过writeshort方法给出了后面的字节数一样。这个值是实际写出的字节数,而不是字符串的长度。在长度之后,字符串中的每个字符都按顺序输出,并对该字符使用修改后的utf-8编码。(…)
两个 writeBytes(String str) 以及 writeChars(String str) 方法应该很有效。

相关问题